wpf - 在 DataTemplates 内绑定(bind)时出现“找不到管理 FrameworkElement ...”警告

标签 wpf warnings datatemplate

绑定(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/

相关文章:

c# - WPF饼图不显示

从 ‘size_t’ 转换为 ‘int’ 可能会改变结果的符号 - GCC , C

c# - WPF 中的数据模板

WPF 数据模板和按钮

c# - WINFORM 或 WPF : How to trigger custom event inside the constructor of the class that emits it

wpf - 如何定义 x :Key for resource in one place and use it in XAML and code behind

c - '&&' 或 '||' 的右侧操作数是可能有副作用的表达式

upload - 在应用程序商店上传应用程序时显示警告消息

wpf - 获取数据模板中的数据项

wpf - 在 XAML 中应用控制模板