Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF FindAncestor性能问题_C#_Wpf_Findancestor - Fatal编程技术网

C# WPF FindAncestor性能问题

C# WPF FindAncestor性能问题,c#,wpf,findancestor,C#,Wpf,Findancestor,在绑定中使用FindAncestor会出现性能问题 我想在子用户控件或ListBoxItem/ListViewItem中使用Base的DataContext 这个问题的替代方案是什么 给父控件一个名称,并使用ElementName=绑定到它,而不是使用FindAncestor遍历可视化树,您可以遍历当前控件的DataContext。要做到这一点,您需要在ViewModels中引用父视图ViewModel。我通常有一个基本的ViewModel类,它有一个属性Parent和Root: public

在绑定中使用FindAncestor会出现性能问题

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

这个问题的替代方案是什么


给父控件一个名称,并使用
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。这是如何产生性能问题的?