TabControls (MVVM) 中的延迟加载 [英] lazy loading in TabControls (MVVM)

查看:18
本文介绍了TabControls (MVVM) 中的延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TabControl,它显示了我的 ViewModel 的集合.ViewModel 和View 的映射是由DataTemplate 实现的.我使用 MVVM 但没有 PRISM(由于历史原因).ViewModel 的 Base 类有一个方法 Load 用于加载信息.我想要做的是只有在选择了当前 ViewModel 对应的 TabItem 时才调用此方法(延迟加载).有任何想法吗?PS 我找到了类似问题的答案 - 延迟加载 WPF 标签内容 但我可以不明白如何在 MVVM 中使用方法 2.

I have an TabControl which displays a collection of my ViewModels. The mapping between ViewModel and View is implemented by DataTemplate. I use MVVM but without PRISM (for historical reasons). The ViewModel’s Base class has a method Load which load information. What I want to do is to call this method only when a TabItem corresponding to the current ViewModel is chosen (lazy loading). Any ideas? PS I found answers to a similar question - Lazy loading WPF tab content but I can’t understand how to use approach 2 in MVVM.

推荐答案

TabItem,因为任何 Selector 项都具有 IsSelected 属性.您可以尝试使用双向绑定将其与视图模型绑定.当模型的 IsSelected 首次设置为 true 时,您可以加载数据.

TabItem as any Selector item has the IsSelected property. You may try to bind it with view model using two-way binding. When model's IsSelected set to true for the first time, you may load your data.

XAML:

<TabControl ...>
    <TabControl.ItemContainerStyle>
        <Style TargetType="{x:Type TabItem}">
            <Setter Property="IsSelected"
                    Value="{Binding Path=IsSelected,Mode=TwoWay}"/>
        </Style>
    </TabControl.ItemContainerStyle>
</TabControl>

示例模型:

public class MyViewModel : INotifyPropertyChanged
{
    private bool _isLoaded;

    private void Load()
    {
        // code
    }

    private bool _isSelected;

    public bool IsSelected
    {
        get
        {
            return this._isSelected;
        }
        set
        {
            if (this._isSelected != value)
            {
                this._isSelected = value;

                if (this._isSelected && !this._isLoaded)
                {
                    this.Load();
                    this._isLoaded = true;
                }

                var propertyChanged = this.PropertyChanged;
                if (propertyChanged != null)
                {
                    propertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
                }
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

这篇关于TabControls (MVVM) 中的延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆