我有一个包含国家/地区列表的XML文件。我在xaml中使用XMLDataProvider来绑定组合框的ItemsSource。我还有一个viewModel,其中包含我想要将所选值绑定到的属性。我试图使用名称空间local:
绑定到viewmodel SelectedValuePath="Country"
SelectedValue="{Binding local:Project.ProjectInfo.CompanyCountry}"
但是我必须为xmlProvider设置DataContext。
有没有办法让绑定在viewModel中工作?
提前致谢。
答案 0 :(得分:0)
如果您的ViewModel是视图的公共属性,您可以命名您的视图并以此方式访问它。
<Window Name="Window"
...>
<ComboBox SelectedValue="{Binding ElementName=Window, Path=ViewModel.Property}" ... />
......或类似的东西。
答案 1 :(得分:0)
将ViewModel放入.Resources并绑定到那个?
<UserControl .... xmlns:local="Project">
<UserControl.Resources>
<local:ProjectInfo x:key="ProjectInfo"/>
</UserControl.Resources>
<UserControl.DataContext>
<XmlObjectDataProvider ... />
</UserControl.DataContext>
<ComboBox ItemsSource="{Binding}" SelectedValuePath="Country" SelectedValue="{Binding CompanyCountry,Source={StaticResource ProjectInfo}}"/>
HTH。基本上你有两个数据源 - 一个在datacontext中,另一个在你的资源中。
编辑:你可以根据需要切换两个,这并不重要。您可以在资源中拥有任意数量的数据源。