在 Binding 中使用FindAncestor有一个关于性能问题的问题。
我想在子用户控件或 ListBoxItem/ListViewItem 中使用 Base 的 DataContext。
这个问题有什么替代方案?
在 Binding 中使用FindAncestor有一个关于性能问题的问题。
我想在子用户控件或 ListBoxItem/ListViewItem 中使用 Base 的 DataContext。
这个问题有什么替代方案?
FindAncestor
您可以向上遍历DataContext
当前控件的,而不是向上遍历 Visual Tree 。为了能够做到这一点,您需要在您ViewModels
的 parent中引用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;
}
}
}
}
在 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
。
为父级命名并使用 绑定到它ElementName=
。