0

在 Binding 中使用FindAncestor有一个关于性能问题的问题。

我想在子用户控件或 ListBoxItem/ListViewItem 中使用 Base 的 DataContext。

这个问题有什么替代方案?

查找祖先

4

2 回答 2

0

FindAncestor您可以向上遍历DataContext当前控件的,而不是向上遍历 Visual Tree 。为了能够做到这一点,您需要在您ViewModels的 parent中引用ViewModel。我通常有一个基ViewModel类,它有一个属性ParentRoot

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

于 2016-01-20T08:56:18.910 回答
0

为父级命名并使用 绑定到它ElementName=

于 2016-01-20T08:08:43.017 回答