我有一個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。我怎樣才能解決這個問題?