我正在通过本教程学习WPF,我坚持在讲座20。我遵循每个步骤,但是我的代码给出了错误
不支持嵌套类型:canvas.top
重点是,它在演讲视频中成功运行
我的XAML代码是:
<Window.Resources>
<local:ThresholdRuleConverter x:Key="ruleConverter" />
</Window.Resources>
<StackPanel>
<TextBox x:Name="txtAmount" Text="{Binding Path=ItemAmount}"
HorizontalAlignment="Stretch"
Tag="{Binding Path=ItemAmount, Mode=OneTime}" Height="35" FontSize="22"
Canvas.Top="{Binding Path=Threshold}">
<TextBox.Background>
<MultiBinding Converter="{StaticResource ruleConverter}" ConverterParameter="Red,Yellow,Green">
<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="Tag" />
<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="{Canvas.Top}" />
<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="Text" />
</MultiBinding>
</TextBox.Background>
</TextBox>
</StackPanel>
我的阈值ruleconverter类是
public class ThresholdRuleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
//define base colors
SolidColorBrush invalidBrush = new SolidColorBrush(Colors.Red);
SolidColorBrush equalBrush = new SolidColorBrush(Colors.Yellow);
SolidColorBrush validBrush = new SolidColorBrush(Colors.Green);
if (parameter != null)
{
string[] definedColors = parameter.ToString().Split(',');
BrushConverter converter = new BrushConverter();
if (definedColors.Length > 0)
{
invalidBrush = converter.ConvertFromString(definedColors[0]) as SolidColorBrush;
if (definedColors.Length > 1)
equalBrush = converter.ConvertFromString(definedColors[1]) as SolidColorBrush;
if (definedColors.Length > 2)
validBrush = converter.ConvertFromString(definedColors[2]) as SolidColorBrush;
}
}
if (values.Length < 3)
return invalidBrush;
try
{
if (values[0] != DependencyProperty.UnsetValue && values[1] != DependencyProperty.UnsetValue
&& values[2] != DependencyProperty.UnsetValue)
{
int oldValue = System.Convert.ToInt32(values[0]);
int thresholdValue = System.Convert.ToInt32(values[1]);
int newValue = System.Convert.ToInt32(values[2]);
if (newValue > oldValue && (newValue - oldValue) <= thresholdValue)
return validBrush;
else if (newValue == oldValue)
return equalBrush;
else
return invalidBrush;
}
return invalidBrush;
}
catch (Exception)
{
return invalidBrush;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
和我的简单txtamount DataContext是
txtAmount.DataContext = new Widget { ItemAmount = 25, Threshold = 50 };
错误在路径
的第二个绑定上发生。<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="{Canvas.Top}" />
任何人都可以告诉我如何在上述方案中的路径中参考 canvas.top 。
解决的一种方法是我可以直接使用它:
<Binding Mode="OneWay" Path="Threshold" />
,但我想通过使用 Canvas.top 来解决我的问题。
谢谢。
而不是这个,
<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="{Canvas.Top}" />
这样使用,
<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="(Canvas.Top)" />
更换了卷曲括号。