【发布时间】:2014-07-10 04:23:04
【问题描述】:
我有一个ComboBox,它绑定到我的视图模型上的ObservableCollection。此集合中的对象类型为LanguageItem 对象。我在ComboBox 的ItemTemplate 中有一个DataTemplate 来自定义用户界面。
在这里,我有一个StackPanel,它有几个控件。这些控件绑定到LanguageItem 对象中的一些属性。一切正常。
这是错误开始的地方。我有两种样式,一种在StackPanel 上,一种在TextBlock 上。这些仅包含一些触发器以根据ComboBoxItem.IsHighlighted 的值更改某些颜色。两个DataTriggers,一个代表真,一个代表假。
现在,由于每个ComboBoxItem 的DataContext 将是我的LanguageItem 对象之一,因此要访问IsHighlighted 属性,我在数据触发器中使用RelativeSource 进行绑定。这是一个例子:
<DataTrigger Value="True"
Binding="{Binding Path=IsHighlighted,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ComboBoxItem}}}">
当我运行我的应用程序时,当我将鼠标悬停在ComboBox 中的不同项目上时,这确实有效并且颜色设置正确。但是在 Visual Studio 的输出窗口中,我可以看到记录的数据绑定错误。这是一个例子:
System.Windows.Data Error: 4 :
Cannot find source for binding with reference 'RelativeSource FindAncestor,
AncestorType='System.Windows.Controls.ComboBoxItem', AncestorLevel='1''.
BindingExpression:Path=IsHighlighted; DataItem=null;
target element is 'TextBlock' (Name='');
target property is 'NoTarget' (type 'Object')
我不明白如果绑定正常,为什么会记录此错误。起初我怀疑这些错误消息是指这些绑定。我把这两种样式都注释掉了,错误就消失了。但正如预期的那样,鼠标悬停时颜色的变化也是如此。
是我对某些东西缺乏了解,还是这是 VS 中的错误?作为参考,这里有一个完整的样式。我的目标是使用 VS 2012 和 Update 4 的 .NET 3.0。
<DataTemplate DataType="{x:Type model:LanguageItem}">
...
<StackPanel.Style>
<Style TargetType="{x:Type StackPanel}">
<Style.Triggers>
<DataTrigger Value="True"
Binding="{Binding Path=IsHighlighted,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBoxItem}}}">
<Setter Property="Background" Value="{StaticResource TitleBrush}"/>
</DataTrigger>
<DataTrigger Value="False"
Binding="{Binding Path=IsHighlighted,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBoxItem}}}">
<Setter Property="Background" Value="{StaticResource BackgroundBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
...
</DataTemplate>
【问题讨论】:
-
绑定发生的顺序并不是你真正能控制的。我用多值转换器遇到了这个问题。但是稍后会使用所有绑定再次调用转换器。
标签: wpf