2013-03-19 88 views
30

结合我得到这个错误:无法找到来源为参照 '的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}}"> 

视图模型坐在如DataContext的用户控件中。 DataGrid的DataContext(坐在UserControl中)是ViewModel中的属性,在ViewModel中我有一个变量,表示是否显示某一行,它的绑定失败,为什么?

这里我的财产:

private bool _isVisible=false; 

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

当涉及到的功能:NotifyPropertyChanged PropertyChanged事件空 - 意味着他无法为绑定注册。

应当指出的是,我有更多的绑定视图模型在这样一个可行的办法,这里有一个例子:

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

回答

49

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

+0

现在我得到这个错误:BindingExpression路径错误:'对象'上找不到'IsVisible'属性'''BindingProxy' – 2013-03-19 08:38:59

+1

哎呀,那应该是Data.IsVisible。 – 2013-03-19 09:14:00

+0

太棒了!它最后工作,非常感谢。 – 2013-03-19 09:20:01