我正在通过this教程学习WPF,我坚持lecture 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>
而我的ThresholdRuleConverter类是
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 来解决我的问题。
感谢。
答案 0 :(得分:1)
而不是这个,
<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="{Canvas.Top}" />
像这样使用,
<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="(Canvas.Top)" />
花括号替换。