簡體   English   中英

如何在不使用集合索引的情況下綁定到集合?

[英]How to bind to a collection without using an index of the collection?

我正在嘗試學習WPF中的MVVM模式,並且遇到綁定和集合的一些問題。 我不喜歡綁定到集合的索引,因為集合發生了變化。

我有MyModelClass : ObservableCollection<MyData>

MyData類具有一個名為DataValue的屬性,用於保存我的自定義信息。 我用MyData對象填充MyModelClass 在視圖模型類( MyViewModel )中,我具有類型為MyModelClass的屬性CurrentData

現在,在這種情況下,我的綁定是組合框。 綁定看起來像這樣:

<ComboBox Name="cmbxData" 
  ItemsSource="{Binding Path=CurrentData}"
  DisplayMemberPath="DataValue"
  SelectedValuePath="DataValue"
  SelectedValue="{Binding Path=CurrentData[0].DataValue}"/>

所有這些都可以正常工作,並且MyViewModel類具有PropertyChanged通知的接口設置。 我需要每隔幾秒鍾刷新一次保存的信息。

我通過在MyModelClass執行以下操作來刷新集合:

public Class MyModelClass : ObservableCollection<MyData>
{
    private static MyModelClass current = null;
    public static MyModelClass Current
    {
        get
        {
             if(current == null)
                 current = new MyModelClass();

             return current;
        }
    }

    private void UpdateModel(MyData newData)
    {
         MyModelClass newModel = new MyModelClass();
         newModel.Add(newData);
         current = newModel;

    }
}

MyViewModel里面是這樣的:

MyModelClass CurrentData = MyModelClass.Current;

我盡力提供盡可能多的代碼並保持簡單。 請讓我知道是否還有更多需要澄清的地方。 感謝您對如何解決我的問題的任何建議。

如果您錯過了它:問題:如何綁定到集合或要在集合中顯示的值,而無需使用上面顯示的索引( SelectedValue="{Binding Path=CurrentData[0].DataValue}" )? 如何解決此問題或更改我的實現以使其正確?

謝謝,

在MyModelClass上添加一個名為“ SelectedData”的屬性或類似的名稱。 然后將該屬性綁定到ComboBox的SelectedItem屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM