【问题标题】:MVVM Pattern in Master-Detail when editing details编辑详细信息时主详细信息中的 MVVM 模式
【发布时间】:2014-06-10 13:43:21
【问题描述】:

我有一个带有一些数据的 ObservableCollection。它们显示为 Master (ListBox) 和 Detail(一些 Labels)。我使用绑定和 IsSynchronizedWithCurrentItem 向所选主项显示正确的详细信息。这一切正常。现在我想编辑一些细节(加载不同的图像)。我在 ViewModel 中实现了一个按钮命令。

但是我怎么知道在 ViewModel 层中选择了哪个项目(UI)?

感谢您的帮助

【问题讨论】:

    标签: c# wpf mvvm master-detail


    【解决方案1】:

    我真的找不到在 MVVM 场景中有用的 IsSynchronizedWithCurrentItem 属性。 只需在 ViewModel 中公开另一个 SelectedItem 属性即可。

    public ItemType SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            // your logic here
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要将 ViewModel 的一个值或 Enumerable 值绑定到 ListBox 的 SelectedItems 属性。

      SelectedItems="{Binding VMProperty}"
      

      http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.selecteditems(v=vs.110).aspx

      如果您只想选择一项,则需要设置:

      SelectionMode="Single"
      SelectedItem="{Binding VMProperty}"
      

      【讨论】:

        【解决方案3】:

        如果我的理解正确,您正在寻找的是以下内容

        <ListBox SelectedItem="{Binding ObjectName, UpdateSourceTrigger=PropertyChanged}"/>
        

        另外,在您的 ViewModel 下,您必须声明以下内容

        public YourObject ObjectName { get; set; }
        

        就这么简单!

        【讨论】:

          【解决方案4】:

          在 UI 中检测当前选择集合中的哪个项目的常规方法是将与集合中的项目相同类型的属性数据绑定到 ListBox.SelectedItem 属性:

          <ListBox ItemsSource="{Binding SomeCollection}" 
              SelectedItem="{Binding SomeProperty}" />
          

          现在,每当用户选择一个新项目时,都会调用 SomeProperty 设置器:

          public YourDataType SomeProperty
          {
              get { return someProperty; }
              set
              {
                  someProperty = value;
                  // The value has just changed
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-08-19
            • 2010-12-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-10-13
            • 2016-08-16
            • 1970-01-01
            相关资源
            最近更新 更多