简体   繁体   中英

How do I Encapsulate a WPF ViewModel/View UserControl as a Control

I've built a WPF UserControl View/ViewModel pair: the view XAML handles the layout and bindings, and the ViewModel handles the logic, in-line with the recommended MVVM pattern.

I would like to be able to re-use this as a control.

How do I hide/encapsulate the ViewModel associated with the view, so that I can use the control as I would a standard control [such as a button] ?

ie How do I hide the control's viewmodel ?

depends on how you bind ViewModel class to the control. if you do like this:

 YourControl()
{
   DataContex = new ViewModel();
}

then I don't see any problems. add reference to your control and use it.

You can create your ViewModel as a StaticResource within your XAML. The problem with setting the DataContext to your ViewModel is that you can't use that you can no longer use your DataContext from the window or page you in which you use the control.

In your XAML declare your ViewModel:

<myNS:MyViewModel x:Key="ViewModel />

Reference your view model within your XAML:

<TextBlock Text="{Binding Source={StaticResource ViewModel}, Path=TextToBind}" />

In your Code Behind you can access and initialize quickly, I usually make a property for easy reference to my view model.

 private MyViewModel viewModel
 {
    get { return this.Resources["ViewModel"] as MyViewModel; }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM