What should be the visibility of the ViewModel elements?

I ran into an interesting problem for which I have not yet found an explanation ...

Given the very simple MVVM application MVVM below, why is a list associated with a combo box only if its visibility in the ViewModel is set to public ?

Changing the visibility of TestList to internal does not cause errors or warnings at compile time, but leaves the combo box blank at run time.

Quote official documentation : internal types or members are only available inside files in the same assembly.

And this problem occurs despite the fact that View and ViewModel are defined in the same assembly.

This is what the code looks like:

Model:

 class TestModel { internal List<string> Musketeers { get; private set; } public TestModel() { Musketeers = new List<string> { "Athos", "Porthos", "Aramis" }; } } 

View:

 <Window x:Class="TestWpfApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid> <ComboBox Width="250" Height="25" ItemsSource="{Binding TestList}" /> </Grid> </Window> 

ViewModel:

 class TestViewModel : INotifyPropertyChanged { TestModel myModel = new TestModel(); public List<string> TestList { get { return myModel.Musketeers; } } // INotifyPropertyChanged members are below ... } 
+8
c # wpf mvvm
source share
2 answers

ViewModel with internal access is available for View , but does not appear in Binding , which really does the work of binding.

{Binding TestList} converted to an instance of the Binding class that does not know about the internal members of your ViewModel class.

+7
source share

This is due to the fact that data binding uses reflection and, in turn, ensures the visibility of elements. Since data binding is implemented outside of your assembly - inside the WPF libraries - it cannot see non-public members.

Binding to a nonexistent element will not lead to a runtime error, but rather to a debugger with a message containing information about the missing element.

+6
source share

All Articles