c# - 数据模板绑定(bind)垃圾邮件输出窗口出现错误 : Cannot find governing FrameworkElemen

标签 c# wpf binding datatemplate

我有问题

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:(no path); DataItem=null; target element is 'SolidColorBrush' (HashCode=48519443); target property is 'Color' (type 'Color')

可以使用以下 xaml 进行复制:

<Window PreviewKeyDown="Window_PreviewKeyDown"
        xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
        ... >
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:ViewModel}">
            <ListBox ItemsSource="{Binding List}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Border Width="20" Height="20">
                            <Border.Background>
                                <SolidColorBrush Color="{Binding diag:PresentationTraceSources.TraceLevel=High}" />
                            </Border.Background>
                        </Border>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DataTemplate>
    </Window.Resources>
    <ContentControl Content="{Binding}" />
</Window>

和CS:

public class ViewModel
{
    public List<Color> List { get; } = new List<Color> { Colors.Red, Colors.Blue, Colors.Green, Colors.Black, Colors.Yellow };
}

public partial class MainWindow : Window
{
    readonly ViewModel _vm = new ViewModel();

    public MainWindow()
    {
        InitializeComponent();
    }

    void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.F1)
            DataContext = _vm;
        if (e.Key == Key.F2)
            DataContext = null;
    }
}

开始,按F1并检查Output窗口(绑定(bind)跟踪已启用,因此您将看到更多内容)。

问题:我该如何修复它们?

错误不会对功能造成问题,但它们会出现在Output窗口中(在实际项目中有很多),这已经是出现问题的迹象。哪个问题?

这里的关键是拥有数据模板并稍后应用它,那么数据模板中的这种绑定(bind)将导致问题。在构造函数中设置 DataContext 不会导致问题。


这里有一些痕迹,如果有人能够理解它并可以给出一些提示:

System.Windows.Data Warning: 56 : Created BindingExpression (hash=45377043) for Binding (hash=28932383)
System.Windows.Data Warning: 58 :   Path: ''
System.Windows.Data Warning: 60 : BindingExpression (hash=45377043): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=45377043): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=45377043): Attach to System.Windows.Media.SolidColorBrush.Color (hash=48519443)
System.Windows.Data Warning: 64 : BindingExpression (hash=45377043): Use Framework mentor <null>
System.Windows.Data Warning: 67 : BindingExpression (hash=45377043): Resolving source 
System.Windows.Data Warning: 69 : BindingExpression (hash=45377043): Framework mentor not found
System.Windows.Data Warning: 65 : BindingExpression (hash=45377043): Resolve source deferred
...
System.Windows.Data Warning: 67 : BindingExpression (hash=45377043): Resolving source 
System.Windows.Data Warning: 69 : BindingExpression (hash=45377043): Framework mentor not found
System.Windows.Data Warning: 67 : BindingExpression (hash=45377043): Resolving source 
System.Windows.Data Warning: 69 : BindingExpression (hash=45377043): Framework mentor not found
System.Windows.Data Warning: 67 : BindingExpression (hash=45377043): Resolving source  (last chance)
System.Windows.Data Warning: 69 : BindingExpression (hash=45377043): Framework mentor not found
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:(no path); DataItem=null; target element is 'SolidColorBrush' (HashCode=48519443); target property is 'Color' (type 'Color')

据我了解,当数据模板创建元素时,找不到用于绑定(bind)到源的mentor(什么是mentor?),因此绑定(bind)创建被推迟。然后它重复几次并因给定错误而失败。但最后它起作用了,也许它继续重复而不追踪它?有什么想法吗?

最佳答案

不幸的是,我无法向您提供有关绑定(bind)错误发生的原因以及绑定(bind)最终起作用的确切细节,但也许我能够对此进行一些说明。

这似乎正在发生:

由于您使用绑定(bind)时未指定源,因此默认情况下框架会尝试使用目标上的 FrameworkElement.DataContextFrameworkContentElement.DataContext 属性作为源用于绑定(bind)。这显然失败了,因为 SolidColorBrush 都不是派生自两者。此外,由于 SolidColorBrush 既不是视觉树的一部分,也不是逻辑树的一部分,因此它无法绑定(bind)到 Border,因此框架无法解析绑定(bind)的源。但不确定在某个时刻源已解析且绑定(bind)正常工作是如何发生的。

但是这个问题有一个解决方案,它是专门为了解决这种情况而引入的,它使用视觉或逻辑树之外的其他方式来解决绑定(bind)源。您需要做的就是将 SolidColorBrush 定义为资源:

<Border Width="20" Height="20">
    <Border.Resources>
        <SolidColorBrush x:Key="BackgroundBrush" Color="{Binding}" />
    </Border.Background>
    <Border.Background>
        <StaticResource ResourceKey="BackgroundBrush" />
    </Border.Background>
</Border>

通过这样做,您会在跟踪中得到一个主要差异,这似乎是不出现 Error: 2:

的关键
...
System.Windows.Data Warning: 65 : BindingExpression (hash=38517915): Resolve source deferred
System.Windows.Data Warning: 95 : BindingExpression (hash=38517915): Got InheritanceContextChanged event from SolidColorBrush (hash=55584612)
...

此解决方案不仅适用于 SolidColorBrush,还适用于派生自 Freezable 的任何类型的对象(画笔、变换等)

但是您必须小心,因为它会产生影响您将Freezable放置在哪个资源字典中。如果您将其放入 Window.Resources 字典中,则源将解析为 Window.DataContext(在您的情况下是一个 ViewModel 实例)。

我的最终假设是,如果您使用此技术,Freezable 上设置的绑定(bind)将被解析就像它们是在资源字典所有者上设置的(由我认为这种方式被称为导师管理元素)。这也适用于使用 RelativeSourceElementName 的绑定(bind)。

关于c# - 数据模板绑定(bind)垃圾邮件输出窗口出现错误 : Cannot find governing FrameworkElemen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40507978/

相关文章:

c# - WPF Infragistics XamDataGrid 窃取滚动焦点

c# - DbContext 因 PrimitiveType != null 错误而崩溃

c# - C# .NET 中的异步 POST 请求

c# - WPF 如何使用 StringConverter 将 slider 的值绑定(bind)到标签的内容?

javascript - React.js,如何避免 var me = this?

c# - ClaimsAuthenticationManager.Authenticate 永远不会被调用

wpf - 在样式 wpf 的 setter 中使用转换器

c# - WPF ListBox 将 SelectedItem 值发送到 View 模型

WPF - 组合框绑定(bind)问题

xcode - 需要调试 Cocoa 绑定(bind)的技巧