Passing one variable to multiple UserControls - WP

2019-09-21 03:23发布

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?

标签: c# wpf mvvm
1条回答
淡お忘
2楼-- · 2019-09-21 03:44

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.

查看更多
登录 后发表回答