2016-09-13 180 views
2

我有一個UserControl barView和相應的ViewModel barViewModel。這個ViewModel有屬性SelectedSomething,它綁定到我的視圖中的不同列表框。綁定SelectedItem更正WPF中的DataContext

如果我有建設這樣的,那麼一切炒鍋罰款:

<UserControl DataContext="barViewModel"> 
    <ListBox ItemsSource="{Binding ObservableCollectionWithItems}" 
      SelectedItem="{Binding SelectedSomething, Mode=TwoWay}"> 
     .... 
    </ListBox> 
</UserControl> 

在這種情況下我的視圖模型與項目的ObservableCollection。

現在我想將我的項目分組。我創建了一個separete類爲:

class ItemsGroup 
{ 
    private string _Name; 
    public string Name {...} 

    private List<Item> _ItemsList; 
    public List<Item> ItemsList {...} 
} 

barViewModel現在包含ItemsGroup對象的observalbe集合。對於這個新的觀點是這樣的:

<UserControl DataContext="barViewModel"> 
<ItemsControl ItemsSource="{Binding ObservalbeCollectionWithItemsGroup}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate DataType="{x:Type test:ItemsGroup}"> 
      <Expander IsExpanded="False"> 
       <Expander.Header> 
        <TextBlock Content="{Binding Name}"/> 
       </Expander.Header> 
       <ListBox ItemsSource="{Binding ItemsList}" Margin="10" 
         SelectedItem="{Binding SelectedSomething, Mode=TwoWay}"> 
        ... 
       </ListBox> 
      </Expander> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

的問題是,列表框的SelectedItem被綁定到父,讓我看看這個錯誤:

System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedSomething' property not found on 'object' ''ItemsGroup' (HashCode=10335672)'. BindingExpression:Path=SelectedSomething; DataItem='ItemsGroup' (HashCode=10335672); target element is 'ListBox' (Name=''); target property is 'SelectedItem' (type 'Object')

我試圖改變的SelectedItem到此:

Text="{Binding SelectedSomething, 
       RelativeSource={RelativeSource Mode=FindAncestor, 
               AncestorType={x:Type UserControl}}}" 

這將刪除錯誤,但我的SelectedSomething是sti不會綁定到ListBox。我怎樣才能解決這個問題?

回答

2

SelectedSomething是在主視圖模型的屬性,以及用戶控件的DataContext被設置爲視圖模型的實例,結合應該是這樣的:

SelectedItem="{Binding DataContext.SelectedSomething, 
       RelativeSource={RelativeSource AncestorType=UserControl}}" 

還請注意,這是不需要在SelectedItem綁定上設置Mode=TwoWay,因爲該屬性默認情況下是雙向綁定的。