在绑定中使用FindAncestor存在性能问题。
我想在子用户控件或ListBoxItem/ListViewItem中使用Base的DataContext。
这个问题的另一种选择是什么?

发布于 2016-01-20 08:08:43
给父程序一个名称,并使用ElementName=绑定到它。
发布于 2016-01-20 08:56:18
与使用FindAncestor遍历Visual不同,您可以遍历当前控件的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;
}
}
}
}在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上。
https://stackoverflow.com/questions/34894112
复制相似问题