wpf 无法找到引用“RelativeSource FindAncestor”的绑定源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15494226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot find source for binding with reference 'RelativeSource FindAncestor'
提问by Hodaya Shalom
I get this error:
我收到此错误:
Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''
on this Binding:
在此绑定上:
<DataGridTemplateColumn Visibility="{Binding DataContext.IsVisible, RelativeSource={RelativeSource AncestorType={x:Type UserControl}},Converter={StaticResource BooleanToVisibilityConverter}}">
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?
ViewModel 位于 UserControl 中的 DataContext。DataGrid 的 DataContext(位于 UserControl 中)是 ViewModel 中的属性,在 ViewModel 中我有一个变量表示是否显示某行,其绑定失败,为什么?
Here my property :
这是我的财产:
private bool _isVisible=false;
public bool IsVisible
{
get { return _isVisible; }
set
{
_isVisible= value;
NotifyPropertyChanged("IsVisible");
}
}
When it comes to the function: NotifyPropertyChanged the PropertyChanged event null - mean he failed to register for the binding.
当涉及到函数时:NotifyPropertyChanged PropertyChanged 事件 null - 意味着他未能注册绑定。
It should be noted that I have more bindings to ViewModel in such a way that works, here is an example:
应该注意的是,我以这种有效的方式对 ViewModel 进行了更多绑定,这是一个示例:
Command="{Binding DataContext.Cmd, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
回答by Cameron MacFarland
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.
DataGridTemplateColumn
不是可视化或逻辑树的一部分,因此没有绑定祖先(或任何祖先),因此RelativeSource
不起作用。
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}}">
And the binding proxy.
和绑定代理。
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));
}
学分。