Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
991 views
in Technique[技术] by (71.8m points)

wpf - lazy loading in TabControls (MVVM)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

Sample model:

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...