简体   繁体   English

WPF ComboBox XML绑定和ViewModel绑定?

[英]WPF ComboBox XML Binding AND ViewModel Binding?

I have an XML file with a list of countries. 我有一个包含国家/地区列表的XML文件。 I use an XMLDataProvider in xaml to bind a combobox's ItemsSource. 我在xaml中使用XMLDataProvider来绑定组合框的ItemsSource。 I also have a viewModel with a property that I wanted to bind the selected value to. 我还有一个viewModel,其中包含我想要将所选值绑定到的属性。 I've tried to bind to the viewmodel using a namespace local: 我试图使用命名空间local绑定到viewmodel:

SelectedValuePath="Country"

SelectedValue="{Binding local:Project.ProjectInfo.CompanyCountry}"

However I had to se the DataContext for the xmlProvider. 但是我不得不为xmlProvider设置DataContext。

Is there a way to get the binding to work in the viewModel? 有没有办法让绑定在viewModel中工作?

Thanks in advance. 提前致谢。

If your ViewModel is a public property of the view you could name your view and get access to it that way. 如果您的ViewModel是视图的公共属性,则可以为视图命名并以此方式访问它。

<Window Name="Window"
        ...>

<ComboBox SelectedValue="{Binding ElementName=Window, Path=ViewModel.Property}" ... />

...or something like that. ...或类似的东西。

Put your ViewModel in your .Resources and bind to that? 将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. HTH。 Basically you have two datasources - one in the datacontext and the other in your resources. 基本上你有两个数据源 - 一个在datacontext中,另一个在你的资源中。

EDIT: You can switch the two if need be, it doesn't really matter. 编辑:你可以切换这两个,如果需要,它并不重要。 You can have as many datasources as you like in your resources. 您可以在资源中拥有任意数量的数据源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM