Passing one variable to multiple UserControls - WP

2019-09-21 03:56发布

问题:

I have a MainWindow and 7 UserControls with their own VM's.

My MainWindow has two Strings (email and language) which I need in all 7 UserControls. I found a solution (simple Dependency Properties for each UserControl) but I don't want to do that 7 times for each UserControl because that doesn't seem right for me. Is there a better way of doing this?

回答1:

If you're using a ViewModelBase class with the INotifyPropertyChanged interface (usually standard in an MVVM app) then simply add you're two strings here. All of you're subsequent ViewModels will inherit these properties, eliminating the need to implement the two properties in each of your ViewModels.

public class ViewModelBase : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public string Email { get; set; }
    public string Language { get; set; }
}

If you mark the class and the properties as abstract, this would force derived classes to override the two properties.



标签: c# wpf mvvm