找不到参考'RelativeSource FindAncestor'的绑定源 [英] Cannot find source for binding with reference 'RelativeSource FindAncestor'

查看:600
本文介绍了找不到参考'RelativeSource FindAncestor'的绑定源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误:

Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''

关于此绑定:

 <DataGridTemplateColumn Visibility="{Binding DataContext.IsVisible, RelativeSource={RelativeSource AncestorType={x:Type UserControl}},Converter={StaticResource BooleanToVisibilityConverter}}">

ViewModel在UserControl中作为DataContext放置. DataGrid的DataContext(位于UserControl中)是ViewModel中的属性,在ViewModel中,我有一个变量,该变量指示是否显示特定的行,其绑定失败,为什么?

The ViewModel is sitting as DataContext in UserControl. The DataContext of the DataGrid (sitting in UserControl) is property within the ViewModel, in ViewModel I have a variable that says whether to show a certain line or not, its binding fails, why?

这是我的财产:

    private bool _isVisible=false;

    public bool IsVisible
    {
        get { return _isVisible; }
        set
        {
            _isVisible= value;
            NotifyPropertyChanged("IsVisible");
        }
    }

关于函数:NotifyPropertyChanged,PropertyChanged事件为null-表示他未能注册绑定.

When it comes to the function: NotifyPropertyChanged the PropertyChanged event null - mean he failed to register for the binding.

应该注意的是,我以可行的方式对ViewModel进行了更多绑定,这是一个示例:

It should be noted that I have more bindings to ViewModel in such a way that works, here is an example:

Command="{Binding DataContext.Cmd, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 

推荐答案

DataGridTemplateColumn不属于可视树或逻辑树,因此没有绑定祖先(或任何祖先),因此RelativeSource不起作用

DataGridTemplateColumn is not part of the visual or logical tree, and therefore has no binding ancestor (or any ancestor) so the RelativeSource doesn't work.

相反,您必须明确为绑定提供源.

Instead you have to give the binding the source explicitly.

<UserControl.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</UserControl.Resources>

<DataGridTemplateColumn Visibility="{Binding Data.IsVisible, 
    Source={StaticResource proxy},
    Converter={StaticResource BooleanToVisibilityConverter}}">

还有绑定代理.

public class BindingProxy : Freezable
{
    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.
    // This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), 
        typeof(BindingProxy), new UIPropertyMetadata(null));
}

信用.

这篇关于找不到参考'RelativeSource FindAncestor'的绑定源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆