我在Visual Studio的输出窗口中绑定一个SolidColorBrush属性时,在DataTemplate内部遇到了这个警告:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=MyColor; DataItem=null; target element is 'SolidColorBrush' (HashCode=22943289); target property is 'Color' (type 'Color')
如果我直接在矩形元素上进行绑定,而不是在DataTemplate之外,那么一切都正常。
有人能解释一下为什么从下面的示例代码中看起来这两种用法会有这样的不同吗:
我的视图:
<UserControl.Resources>
<vm:TestViewModel x:Key="_myTestVM"/>
<DataTemplate x:Key="testVMDataTemplate">
<Grid>
<Rectangle Height="30" Width="200" Margin="5">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding Path=MyColor}" />
</Rectangle.Fill>
</Rectangle>
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid>
<StackPanel DataContext="{StaticResource _myTestVM}">
<!-- Binding *outside* the DataTemplate = works fine -->
<Rectangle Height="30" Width="200" Margin="5">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding Path=MyColor}"/>
</Rectangle.Fill>
</Rectangle>
<!-- Binding *inside* the DataTemplate = output warning -->
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource testVMDataTemplate}"/>
</StackPanel>
</Grid>
我的ViewModel(TestViewModel):
public class TestViewModel {
private Color _color = Colors.Green;
public Color MyColor {
get { return _color; }
}
public TestViewModel() {
}
}
更新:
显然与为SolidColorBrush绑定Color属性有关。如果我在一个RotateTransform对象上绑定Angle属性,同样的事情也会发生。
提前感谢。
FrameworkElement
,但它是一个DependencyObject
,而Color
是一个DependencyProperty
。对它的绑定工作正常 - 直到你在没有传递DataContext
的上下文中。为了我想要的,我需要在样式中的Binding
中使用DataContext
(基于其他颜色构建SolidColorBrush
),然后遇到了这个问题(无法解决;必须重新设计),但是当直接将新的SolidColorBrush
分配给<Grid.Background>
时,我可以很愉快地绑定到 Color。 - tobriand