C# WPF FindAncestor性能问题
在绑定中使用FindAncestor会出现性能问题 我想在子用户控件或ListBoxItem/ListViewItem中使用Base的DataContext 这个问题的替代方案是什么C# WPF FindAncestor性能问题,c#,wpf,findancestor,C#,Wpf,Findancestor,在绑定中使用FindAncestor会出现性能问题 我想在子用户控件或ListBoxItem/ListViewItem中使用Base的DataContext 这个问题的替代方案是什么 给父控件一个名称,并使用ElementName=绑定到它,而不是使用FindAncestor遍历可视化树,您可以遍历当前控件的DataContext。要做到这一点,您需要在ViewModels中引用父视图ViewModel。我通常有一个基本的ViewModel类,它有一个属性Parent和Root: public
给父控件一个名称,并使用
ElementName=
绑定到它,而不是使用FindAncestor
遍历可视化树,您可以遍历当前控件的DataContext
。要做到这一点,您需要在ViewModels
中引用父视图ViewModel
。我通常有一个基本的ViewModel
类,它有一个属性Parent
和Root
:
public abstract class ViewModel : INotifyPropertyChanged
{
private ViewModel parentViewModel;
public ViewModel(ViewModel parent)
{
parentViewModel = parent;
}
/// <summary>
/// Get the top ViewModel for binding (eg Root.IsEnabled)
/// </summary>
public ViewModel Root
{
get
{
if (parentViewModel != null)
{
return parentViewModel.Root;
}
else
{
return this;
}
}
}
}
公共抽象类ViewModel:INotifyPropertyChanged
{
私有视图模型parentViewModel;
公共视图模型(视图模型父对象)
{
parentViewModel=父对象;
}
///
///获取用于绑定的top ViewModel(例如Root.IsEnabled)
///
公共视图模型根
{
得到
{
if(parentViewModel!=null)
{
返回parentViewModel.Root;
}
其他的
{
归还这个;
}
}
}
}
在XAML中,您可以替换以下内容:
<ComboBox x:Name="Sector"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.SectorList}"
SelectedValuePath="Id"
SelectedValue="{Binding SectorId, Mode=TwoWay}" />
据此:
<ComboBox x:Name="Sector"
ItemsSource="{Binding Root.SectorList}"
SelectedValuePath="Id"
SelectedValue="{Binding SectorId, Mode=TwoWay}" />
一个要求是:
Root
属性必须始终存在于最顶层的ViewModel
我认为FindAncestor是一种方法,因为ListBoxItems有自己的DataContext。这是如何产生性能问题的?