控制内容控件的MVVM ListBox

时间:2009-12-14 22:37:26

标签: wpf mvvm binding listbox

我已经围着这个圈子走了几天,我希望WPF大师可以看到我哪里出错了。

我在代码中设置了CurrentViewModel。我的ListBox的Selected项和ContentControl的Content正确绑定。但是,当通过UI更改列表框中的选定项目时,正在设置CurrentViewModel,但内容控件未更新。

我正在使用数据模板来映射我的视图和视图模型。

    <DataTemplate DataType="{x:Type ViewModel:MyViewModel}">
       <View:MyView />
    </DataTemplate>

我有一个ListBox,它绑定到一个可观察的ViewModels集合。 Selected Item绑定到当前视图模型。

 <ListBox ItemsSource="{Binding MyViewModelCollection}" DisplayMemberPath="DisplayName" SelectedItem="{Binding CurrentViewModel, Mode=TwoWay}"/>

我还有一个内容控件,它也绑定到CurrentView模型

 <ContentControl Content="{Binding CurrentViewModel, Mode=TwoWay}"/>

这是他们都绑定的属性

        public MyViewModel CurrentViewModel
    {
        get
        {
            return _currentViewModel;
        }
        set
        {
            if (_currentViewModel== value) return;

            _currentViewModel= value;
            OnPropertyChanged("CurrentViewModel");
        }
    }

为了清晰起见,我编辑了名称并删除了格式信息。

非常感谢任何帮助。

干杯,

丹尼尔

编辑:浏览了How can I debug WPF bindings?链接。我在Content绑定上设置了一个断点,它确实只在首次设置绑定时才被调用一次。

1 个答案:

答案 0 :(得分:4)

您不应将TwoWay设置为ContentControl上的模式:

<ContentControl Content="{Binding CurrentViewModel, Mode=OneWay}"/>

这是因为您打算将ContentControl 读取值,但不要它。


另外,您还可以将ContentControl绑定到集合中当前选定的项目,而不是通过执行此操作将其绑定到该属性:

<ListBox ItemsSource="{Binding MyViewModelCollection}" 
         DisplayMemberPath="DisplayName" 
         IsSynchronizedWithCurrentItem="True"/>

<ContentControl Content="{Binding MyViewModelCollection/}"/>

集合末尾的“斜杠”(/)表示集合中选择的当前项目,并设置当前项目属性与设置IsSynchronizedWithCurrentItem等于true一样简单。

很多时候我发现这个组合,我真的不需要我的视图模型上的额外属性。

无论如何,我希望这有帮助。

相关问题