2013-03-20 30 views
1

我有一個ViewModels列表,每個列表都包含一個列表。當在Caliburn Micro的ViewModels列表中選擇ViewModel時交換ListBox上的綁定?

我想將此列表綁定到視圖中的列表框,以便我可以設置SelectedViewModel,並且視圖中的列表框現在顯示新的SelectedViewModel中的條目。這也應該保留選擇。

是否可以用現有的Caliburn Micro約定來做到這一點,還是我必須明確說明這一點?

例如:

我有稱爲vmList含有兩個的ViewModels,FruitVeg的ViewModels的列表。

ViewModel Fruit包含列表["Apple", "Pear"]

ViewModel Veg包含列表["Carrot", "Cabbage"]

Fruit是當前SelectedViewModel所以目前我的觀點的列表框應該顯示:

Apple 
*Pear* 

Pear目前ListBox中選定的項目。

現在我設置VegSelectedViewModel和我查看更新,以顯示:

*Carrot* 
Cabbage 

Carrot目前ListBox中選定的項目。現在 如果我設置Fruit回作爲SelectedViewModel我查看應該更新顯示:

Apple 
*Pear* 

哪裏Pear仍ListBox中選定的項目。

回答

1

這應該是可能的 - 最簡單的功能是使用CM約定綁定列表內容,並且還爲列表提供SelectedItem綁定。既然你要跟蹤每個VM中的最後一個選擇的項目,你需要密切關注太(無論是在虛擬機本身或在主VM)

因此,解決辦法可能是:

public class ViewModelThatHostsTheListViewModel 
{ 
    // All these properties should have property changed notification, I'm just leaving it out for the example 
    public PropertyChangedBase SelectedViewModel { get; set; } 

    public object SelectedItem { get; set; } 

    // Dictionary to hold last selected item for each VM - you might actually want to track this in the child VMs but this is just one way to do it 
    public Dictionary<PropertyChangedBase, object> _lastSelectedItem = new Dictionary..etc() 

    // Keep the dictionary of last selected item up to date when the selected item changes 
    public override void NotifyOfPropertyChange(string propertyName) 
    { 
     if(propertyName == "SelectedItem") 
     { 
      if(_lastSelectedItem.ContainsKey(SelectedViewModel)) 
       _lastSelectedItem[SelectedViewModel] = SelectedItem; 
      else 
       _lastSelectedItem.Add(SelectedViewModel, SelectedItem); 
     } 
    } 
} 

然後在你的XAML

<ListBox x:Name="SelectedViewModel" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" /> 

顯然設置你的項目模板這裏結合於一個的ViewModels共同財產(使用如DisplayNameIHaveDisplayName界面讓事情變得漂亮和集成)

編輯:

只是一個快速的注意:如果你的虛擬機本身不是List對象,而是包含一個列表,那麼你可能需要顯式綁定列表項的ListBox但它取決於你的ItemTemplate(你根據ContentControl慣例綁定,可以讓CM繼續爲虛擬機解析虛擬機和視圖)

<ListBox ItemsSource="{Binding SelectedViewModel.ListItems}" ...etc /> 
+0

謝謝!我會試試這個:)... – toofarsideways 2013-03-21 21:34:21

相關問題