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

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

问题描述

我有一个TabControl,它显示我的ViewModels的集合. 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,因为任何选择器项都具有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天全站免登陆