首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF FindAncestor性能问题

WPF FindAncestor性能问题
EN

Stack Overflow用户
提问于 2016-01-20 07:38:39
回答 2查看 379关注 0票数 0

在绑定中使用FindAncestor存在性能问题。

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

这个问题的另一种选择是什么?

EN

回答 2

Stack Overflow用户

发布于 2016-01-20 08:08:43

给父程序一个名称,并使用ElementName=绑定到它。

票数 0
EN

Stack Overflow用户

发布于 2016-01-20 08:56:18

与使用FindAncestor遍历Visual不同,您可以遍历当前控件的DataContext。要做到这一点,您需要在ViewModels中引用父ViewModel。我通常有一个基类ViewModel,它有一个属性ParentRoot

代码语言:javascript
复制
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中,您可以替换以下内容:

代码语言:javascript
复制
<ComboBox x:Name="Sector" 
                 ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.SectorList}" 
                 SelectedValuePath="Id" 
                 SelectedValue="{Binding SectorId, Mode=TwoWay}" />

通过这一点:

代码语言:javascript
复制
<ComboBox x:Name="Sector" 
                 ItemsSource="{Binding Root.SectorList}" 
                 SelectedValuePath="Id" 
                 SelectedValue="{Binding SectorId, Mode=TwoWay}" />

一个要求是:Root属性总是存在于最顶层的ViewModel上。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34894112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档