How to inherit ViewModel class to UserControl?

时间:2018-02-03 11:02:19

标签: c# wpf mvvm user-controls

Suppose that I've a ViewModel class with different property such as:

//MainVm will inherit ViewModel that contains IPropertyChanged implementation
public class MainVM : ViewModel 
{
     publi bool Foo { get; set; } 
}

I instatiated this class on the main controller in this way:

MainController mc;

public MaiWindow()
{
    mc = new MainController(); 
    DataContext = mc;
    InitializeComponent();
}

the MainController have this implementation:

public class MainController : MainVM 
{
    some methods
}

so each time I need to access to a property of MainController on each UserControls I need to do: Application.Current.MainWindow.mc.Foo

and this is't elegant at all.

Is possible access to the property of specific ViewModel without call the code line above?

Thanks.

UPDATE

For add more details and clarification to this question: so in my UserControl I need to access to the Foo property that is part of MainVM. I'm spoke about the UserControl xaml code (not the controller of the UserControl), this is an example:

public partial class ControlName : UserControl
{
    public ControlName()
    {
       InitializeComponent();
    }

    public btnAdd_Click(object sender, RoutedEventArgs e)
    {
       //Suppose that I need to access to the property Foo of MainVM here
       //I need to access to MainWindow instance like this:
       Application.Current.MainWindow.mc.Foo

       //isn't possible instead access to the property directly inherit the class, like:
       MainVm.Foo 
    }
}

1 个答案:

答案 0 :(得分:1)

为了获得App-Wide的配置,您可以使用

  ConfigurationManager.AppSettings["Whatever"];

这些设置位于App.Config中,格式如下

<appSettings>
    <add key="Whatever" value="Hello" />
</apSettings>

但正如我所说,你有一个允许用户更改设置的ViewModel,在这种情况下你应该去:

Properties.Settings.Default.myColor = Color.AliceBlue; 

您的ViewModel可以将此属性公开为:

public Color MyColor
{
    get {
       return Properties.Settings.Default.myColor;
    }

    set {
        Properties.Settings.Default.myColor = value; RaisePropertyChanged();
    }
}

public void Persist()
{
    Properties.Settings.Default.Save();
    // Raise whatever needed !
}

您也可以从其他ViewModel访问这些设置:

Properties.Settings.Default.myColor

在这里查看https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/using-application-settings-and-user-settingshttps://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-create-application-settings