开发者

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

开发者 https://www.devze.com 2023-01-30 05:58 出处:网络
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'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 t开发者_运维问答hat I can use the control as I would a standard control [such as a button] ?

i.e. 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; }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消