ViewModel成员的可见性应该是什么?

时间:2013-03-13 21:08:48

标签: c# wpf mvvm

我遇到了一个有趣的问题,我还没有找到任何解释......

鉴于下面非常简单的MVVM WPF应用程序,为什么只有在ViewModel中的可见性设置为public时,列表才会绑定到组合框?

TestList可见性更改为internal会在编译时不会引发错误或警告,但会在运行时将组合框留空。

引用the official documentationinternal类型或成员只能在同一程序集中的文件中访问。

尽管View和ViewModel是在同一个程序集中定义的,但这个问题仍在发生。

以下是代码的外观:

型号:

class TestModel
{
    internal List<string> Musketeers { get; private set; }

    public TestModel()
    {
        Musketeers = new List<string> { "Athos", "Porthos", "Aramis" };
    }
}

查看:

<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>

视图模型:

class TestViewModel : INotifyPropertyChanged
{
    TestModel myModel = new TestModel();

    public List<string> TestList
    {
        get
        {
            return myModel.Musketeers;
        }
    }

    // INotifyPropertyChanged members are below ...
}

2 个答案:

答案 0 :(得分:7)

对于ViewModelinternal具有View访问权限的{Binding TestList}可见,但Binding类不可见,这确实使绑定有效。

Binding已转换为internal类实例,该实例不了解ViewModel类的{{1}}成员。

答案 1 :(得分:6)

这是因为数据绑定使用反射,反过来又会影响项目的可见性。由于数据绑定是在程序集之外实现的 - 在WPF库中 - 它无法看到非公共成员。

绑定到不存在的成员不会发出运行时错误,而是发出一个调试输出,其中包含一条消息,其中包含有关缺少成员的详细信息。