【发布时间】:2011-12-17 02:14:08
【问题描述】:
绑定到 DataTemplate 中的 SolidColorBrush 属性时,我在 Visual Studio 输出窗口中收到此警告:
System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。绑定表达式:路径=我的颜色;数据项=空;目标元素是“SolidColorBrush”(HashCode=22943289);目标属性是“颜色”(输入“颜色”)
如果我直接在矩形元素上绑定,在 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>
我的视图模型(TestViewModel):
public class TestViewModel {
private Color _color = Colors.Green;
public Color MyColor {
get { return _color; }
}
public TestViewModel() {
}
}
更新:
这显然与绑定 SolidColorBrush 的 Color 属性有关。如果我将 Angle 属性绑定到 RotateTransform 对象上,也会发生同样的事情。
提前致谢。
【问题讨论】:
标签: wpf warnings datatemplate