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

Hod*_*lom 35 wpf binding mvvm

我收到此错误:

Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''
Run Code Online (Sandbox Code Playgroud)

在这个绑定:

 <DataGridTemplateColumn Visibility="{Binding DataContext.IsVisible, RelativeSource={RelativeSource AncestorType={x:Type UserControl}},Converter={StaticResource BooleanToVisibilityConverter}}">
Run Code Online (Sandbox Code Playgroud)

ViewModel作为DataContext在UserControl中.DataGrid的DataContext(坐在UserControl中)是ViewModel中的属性,在ViewModel中我有一个变量,表示是否显示某一行,其绑定失败,为什么?

我的财产:

    private bool _isVisible=false;

    public bool IsVisible
    {
        get { return _isVisible; }
        set
        {
            _isVisible= value;
            NotifyPropertyChanged("IsVisible");
        }
    }
Run Code Online (Sandbox Code Playgroud)

当涉及到函数时:NotifyPropertyChanged PropertyChanged事件为null - 意味着他未能注册绑定.

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

Command="{Binding DataContext.Cmd, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 
Run Code Online (Sandbox Code Playgroud)

Cam*_*and 68

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

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

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

<DataGridTemplateColumn Visibility="{Binding Data.IsVisible, 
    Source={StaticResource proxy},
    Converter={StaticResource BooleanToVisibilityConverter}}">
Run Code Online (Sandbox Code Playgroud)

和绑定代理.

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));
}
Run Code Online (Sandbox Code Playgroud)

积分.

  • @Will ElementName使用逻辑树.当元素不使用逻辑树时,您就是SOL.http://stackoverflow.com/questions/705853/binding-elementname-does-it-use-visual-tree-or-logical-tree (3认同)
  • 哎呀,那应该是 Data.IsVisible。 (2认同)