sammarcow
sammarcow

Reputation: 2956

Use of FrameworkElement.FindResource("myResource") in WPF

Following MVVM, I have an object persisted with the existence of a UI Window, object defined in XAML. This object represents the ModelView so it contains the controls which can modify the model. I am finding myself calling FrameworkElement.FindResource("myResource") for every user control. What is the proper way to grab the instance of this object?

XAML:

<p:MyModelView x:Key="modelView" />

CodeBehind:

//for every control I call:
public void SomeEventHandler(object _sender, EventArgs _someEventArgs) {
    MyModelView repeatedCode= this.FindResource("modelView")
    repeatedCode.DoSomeModificationRelatedToControl(args[] someArgs);
}

Upvotes: 0

Views: 1399

Answers (1)

Sphinxxx
Sphinxxx

Reputation: 13017

If you need your ViewModel a lot of places in your View code-behind, create and keep the ViewModel in a variable in the code-behind instead of creating it as a resource in your Xaml. For example:

public partial class MainWindow : Window
{
    private MainViewModel _vm;

    public MainWindow()
    {
        InitializeComponent();

        _vm = new MainViewModel()
        {
            Name = "MyViewModel",
            ...
        };
        this.DataContext = _vm;
    }

That last line is important - by making the ViewModel the View's DataContext, you can bind to it in Xaml like normal.

Now, your event handlers get at least a line or two shorter:

public void SomeEventHandler(object sender, EventArgs someEventArgs)
{
    _vm.DoSomeModificationRelatedToControl(someArgs);
}

Upvotes: 1

Related Questions