开发者

Setting RelativeSource correctly

开发者 https://www.devze.com 2023-04-04 11:09 出处:网络
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

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}"
0

精彩评论

暂无评论...
验证码 换一张
取 消