I have a ChildUserControl
with view-model like this:
public class ChildViewModel
{
public ChildViewModel(HugeSettings settings)
{
// process settings
}
public int SelectedItemsCount { get; internal set; }
// ... and many other properties which should be read-only from outside.
}
When all controls are in single project, ParentUserControl
will use ChildUserControl
like this:
<ParentUserControl ... >
<ChildUserControl DataContext="{Binding ChildViewModel}" />
</ParentUserControl>
And view-model:
public class ParentViewModel
{
public ParentViewModel()
{
this.ChildViewModel = new ChildViewModel(new HugeSettings());
}
// INotifyPropertyChanged implementation omitted
public ChildViewModel ChildViewModel { get; set; }
}
In this scenario, I can initialize ChildViewModel
simply with constructor, and I can get any ChildViewModel
property directly inside ParentViewModel
without worrying whether any views or user controls exists.
The problem is that ChildUserControl
needed to be placed into separate library for sharing with other applications (they will use ChildUserControl
as third-party control). In that case foreign program shouldn't directly manipulate ChildViewModel
, because third-party user control normally should be used like this:
<ForeignUserControl ... >
<ChildUserControl HugeSettings="{Binding Setting}" SelectedItemsCount="{Binding Count, Mode=OneWayToSource}" />
</ForeignUserControl>
As soon as I have many read-only properties besides SelectedItemsCount
, it seems that I have only one choice: create dependency properties in UserControlChild
's code-behind and connect them with corresponding view-model's properties.
Is this approach correct? Does better approach exists?
Update
Googling "mvvm third party user controls" gives me this question with very similar issue. There asker decided to use dependencies properties in code-behind.
So I have a choice:
1. Create DP in code-behind for every needed property in view-model and link each pair. (violates MVVM?)
2. Just move all view-model logic to code-behind and convert properties to DP. Definitely violated MVVM, but there is opinion that "MVVM is not a good choice if you are developing a UserControl that will be consumed by others".
What should I prefer? Is there another choice?