在DataTemplates中绑定时,“无法找到管理FrameworkElement ...”警告

时间:2011-10-28 07:13:21

标签: wpf warnings datatemplate

在DataTemplate 中的SolidColorBrush属性上绑定时,我在Visual Studio输出窗口中收到此警告:

  

System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。 BindingExpression:路径= MyColor;的DataItem = NULL; target元素是'SolidColorBrush'(HashCode = 22943289); target属性为'Color'(类型'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 属性,也会发生同样的事情。

提前致谢。

1 个答案:

答案 0 :(得分:11)

使用DataContext绑定默认数据源不适用于SolidColorBrush类型,因为它们不是框架元素。此外,它们是可冻结的,您不能通过基于数据上下文的颜色绑定动态更改颜色。

您必须通过将颜色转换为纯色画笔的转换器将颜色绑定到背景填充。

 <TextBlock Background="{Binding MyColor,
                                Converter={StaticResource ColorToBrushConverter}}" />

或者使用Color作为DynamicResource并在Solid Color Brush中引用它。

ControlTemplate Storyboard color animation problem