WPF User Control hell with MVVM and Dependency Properties

前端 未结 4 532
醉酒成梦
醉酒成梦 2020-12-09 10:41

This is what I\'m trying to do:

  • I\'m writing a UserControl that I want to be consumed by other developers.
  • I want end users to be able

4条回答
  •  醉话见心
    2020-12-09 11:06

    You should separate the two use cases:

    1. The (user) control that will be consumed by other developers.
    2. The user control that will be consumed by your application.

    Importantly, the latter depends on the former - not vice versa.

    Use case 1 would use dependency properties, template bindings, all the things that go into making a regular WPF control:

    MyControl.cs:

    public class MyControl : Control
    {
        // dependency properties and other logic
    }
    

    Generic.xaml:

    
        
    
    

    You would then define use case 2 as:

    MyViewModel.cs:

    public class MyViewModel : ViewModel
    {
        // properties and business logic
    }
    

    MyView.xaml:

    
        
    
    

    Best of both worlds with a clean separation. Other developers depend only on the control, which could (and probably should) be in a completely different assembly than your view model and view.

提交回复
热议问题