绑定(bind) DataTemplate 内的 SolidColorBrush 属性时,我在 Visual Studio 输出窗口中收到此警告:
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')
如果我直接绑定(bind)在 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>
我的 View 模型(TestViewModel):
public class TestViewModel {
private Color _color = Colors.Green;
public Color MyColor {
get { return _color; }
}
public TestViewModel() {
}
}
更新:
它显然与绑定(bind) SolidColorBrush 的 Color 属性有关。如果我在 RotateTransform 对象上绑定(bind) Angle 属性,也会发生同样的事情。
提前致谢。
最佳答案
与默认数据源绑定(bind)为 DataContext
不适用于 SolidColorBrush
类型,因为它们不是框架元素。此外,它们是可卡住的,并且不允许您通过基于数据上下文的颜色绑定(bind)动态更改它们的颜色。
您必须通过将颜色转换为纯色画笔的转换器将颜色绑定(bind)到背景填充。
<TextBlock Background="{Binding MyColor,
Converter={StaticResource ColorToBrushConverter}}" />
或使用颜色作为
DynamicResource
并引用纯色画笔。ControlTemplate Storyboard color animation problem
关于wpf - 在 DataTemplates 内绑定(bind)时出现“找不到管理 FrameworkElement ...”警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7926204/