0
votes

How to pass parameters to usercontrol's viewmodel through window's xaml? I am using MVVM pattern. I have tried creating a dependency property as below. But passing it in constructoe of viewmodel throws "nonstatic properties cannot be field initializers" exception. xaml.cs of usercontrol

public partial class SomeView : UserControl
{   
    SomeViewModel vm = new SomeViewModel(ForeColor);

    public SomeView()
    {
        InitializeComponent();
        this.DataContext = vm;
    }

    public Color ForeColor
    {
        get { return (Color)this.GetValue(ForeColorProperty); }
        set { this.SetValue(ForeColorProperty, value); }
    }

    public static readonly DependencyProperty ForeColorProperty = DependencyProperty.Register("ForeColor", typeof(Color), typeof(SomeView ));
}

and this is how I am calling the user control

 <local:SomeView ForeColor="{Binding Foreground}"/>

Foreground is a property of type System.Drawing.Color

2

2 Answers

0
votes

As the error stated you cannot refer instance fields from field initializers.

Move the initialization logic to constructor instead:

SomeViewModel vm;

public SomeView()
{
    InitializeComponent();
    vm = new SomeViewModel(ForeColor);
    this.DataContext = vm;
}
0
votes

I would suggest you to always keep the View's code behind as simple as possible, making this way a cleaner app and keeping in mind the MVVM pattern concept.

Based on my understanding, you would want to update the property which has changed on the View to its ViewModel. Otherwise, you could just define the property in the ViewModel without passing it from the View.

Therefore, defining the Property on the ViewModel anyway, you could update its value by specifying the Binding Mode as "OneWayToSource" or "TwoWay". No Property instantiation would be needed on the View's code behind for passing through parameter. The Binding with its DataContext would do the work. In addition, to get these binding modes to work, you may set the UpdateSourceTrigger property on the Binding block.

You can find more information on the following MSDN site:

I hope this helped you, Regards.