无法找到引用'RelativeSource FindAncestor'的绑定源

时间:2013-03-19 08:00:28

标签: wpf mvvm binding

我收到此错误:

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作为DataContext在UserControl中。 DataGrid的DataContext(坐在UserControl中)是ViewModel中的属性,在ViewModel中我有一个变量,表示是否显示某一行,其绑定失败,为什么?

这是我的财产:

    private bool _isVisible=false;

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

说到函数:NotifyPropertyChanged PropertyChanged事件为null - 意味着他没有注册绑定。

应该注意的是,我有更多的ViewModel绑定方式,这是一个例子:

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

1 个答案:

答案 0 :(得分:66)

DataGridTemplateColumn不是视觉或逻辑树的一部分,因此没有绑定祖先(或任何祖先),因此RelativeSource不起作用。

相反,您必须明确地为绑定提供绑定。

<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));
}

Credits