无法找到引用“RelativeSource FindAncestor"的绑定源 [英] Cannot find source for binding with reference '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
作为 DataContext
位于 UserControl
中.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屋!