Setting RelativeSource correctly
I have a combo box on a xaml form (Main开发者_如何学CWindow).
I set the Items source to an ObservableCollection in the code behind. To populate the Combo box I used Relative Source (it sits inside an ItemsControl), which worked great (without it, if did not populate):
ItemsSource="{Binding SelectableItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
I have now factored out the ObservableCollection into a seperate View Model Class, named 'MainWindowViewModel', the combo box does not populate.
I have set the DataContext of the MainWindow to my ViewModel and have checked that it populates other controls as expected, which it does.
How should I construct the RelativeSource so the combo box populates?
Thanks
Joe
I needed to add the Path at the end, thus:
ItemsSource="{Binding SelectableItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.SelectableItems}"
You do not want to use a RelativeSource
any longer. If you don't specify a RelativeSource
(or Source
, or ElementName
), then the binding will resolve against the current DataContext
. Since the DataContext
is inherited, your ItemsControl
obtains its DataContext
from the parent Window
. Thus, this binding will resolve against your view model.
ItemsSource="{Binding SelectableItems}"
精彩评论