[英]Binding from parents Viewmodel
I have a view that has a listbox
in it. 我有一个其中有一个
listbox
的视图。 I have the listbox
bound to a collection of ListBoxViewModel which is a property of MainViewModel. 我将
listbox
绑定到ListBoxViewModel的集合,该集合是MainViewModel的属性。 I then have a dataTemplate
for the listbox
in which im binding to the properties of the ListBoxViewModel. 然后,我有一个
listbox
的dataTemplate
,其中IM绑定到ListBoxViewModel的属性。 The view that contains the listbox has datacontext set to the mainVeiwModel. 包含列表框的视图的datacontext设置为mainVeiwModel。 How can I bind to properties of the MainViewModel in the
dataTemplate
of the listbox
that has its ItemSource
bound to the collection of ListBoxVIewModels? 如何绑定到其
ItemSource
绑定到ListBoxVIewModels集合的listbox
的dataTemplate
中MainViewModel的属性?
This combobox
is in the listBox
datatemplate
which has its itemsoucrce
bound to the collection of ListBoxViewModels. 此
combobox
位于listBox
datatemplate
,其datatemplate
itemsoucrce
绑定到itemsoucrce
的集合。 Notice im trying to bind to MainViewModel properties as well as ListBoxViewModel properties with in the datatemplate
请注意,我尝试绑定到MainViewModel性能以及ListBoxViewModel性质与在
datatemplate
<ListBox ItemSource="{Binding Path=CollectionOfListBoxViewModelsInMainViewModel}"
<DataTemplate>
.....
<ComboBox Margin="6"
Width="300"
IsEditable="True"
ItemsSource="{Binding Path=MainViewModelProperty}" //binding not working
SelectedItem="{Binding ListBoxViewModelProperty}" //binding works
Text="{Binding ListBoxViewModelProperty, UpdateSourceTrigger=LostFocus}"/> //binding works
.....
</DataTemplate>
</ListBox>
Simplest way: 最简单的方法:
<YOURWINDOW x:Name="MyWindow">
<ListBox ItemSource="{Binding Path=CollectionOfListBoxViewModelsInMainViewModel}"
<DataTemplate>
.....
<ComboBox Margin="6"
Width="300"
IsEditable="True"
ItemsSource="{Binding ElementName=MyWindow, Path=DataContext.MainViewModelProperty}"
SelectedItem="{Binding ListBoxViewModelProperty}" //binding works
Text="{Binding ListBoxViewModelProperty, UpdateSourceTrigger=LostFocus}"/> //binding works
.....
</DataTemplate>
</ListBox>
</YOURWINDOW>
1) Remember that MyWindow must have set DataContext to MainViewModel. 1)请记住,MyWindow必须将DataContext设置为MainViewModel。 You can use any UI element, it doesn't have to be Window.
您可以使用任何UI元素,而不必是Window。 2) Second solution is to use RelativeSource instead of ElementName.
2)第二种解决方案是使用RelativeSource代替ElementName。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.