Binding UserControl View model on MainWindow with MVVM

前端 未结 1 1541
半阙折子戏
半阙折子戏 2020-12-20 04:35

I am newbie to WPF and MVVM and I am trying to learn how WPF working with MVVM. For that, I have made a sample as follows

UserControl1.xaml

相关标签:
1条回答
  • 2020-12-20 04:55

    You got a general misunderstanding here about MVVM, Views and UserControls.

    A UserControl is a reusable piece of code, that is not specific to one kind of application. That being said, there is no UserControl1ViewModel, when you create a new UserControl.

    A UserControl is self-sustained and all the logic your user control needs goes in there in code behind. To make it clear, this is not a violation of MVVM pattern. MVVM pattern applies to Views and ViewModels and how they interact.

    There is a subtle difference between a View (pure XAML, no logic). Views also often inherit from UserControl, but a View is only good in the application you are developing right now. You are very unlikely to be able to reuse this in another application.

    That's a difference, between the UserControl. For example, a calendar user control is reusable and all the logic to choose and display the calendar is part of it's control code behind and you can use it in many kind of applications.

    When you create a UserControl which uses data-bindings, you need to expose dependency properties in your user control, on an date-picker user control this may be MinDate, MaxDate, SelectedDate, FirstDayOfTheWeek (Sunday or Monday) and/or properties that control the formatting and hide all other properties inside your UserControls XAML (by not exposing them via Dependency Properties).

    0 讨论(0)
提交回复
热议问题