c# - WPF ComboBox XML 绑定(bind)和 ViewModel 绑定(bind)?

标签 c# wpf data-binding binding combobox

我有一个包含国家列表的 XML 文件。我在 xaml 中使用 XMLDataProvider 来绑定(bind)组合框的 ItemsSource。我还有一个 viewModel,它有一个我想将所选值绑定(bind)到的属性。我尝试使用本地命名空间绑定(bind)到 View 模型:

SelectedValuePath="国家"

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

但是我必须为 xmlProvider 设置 DataContext。

有没有办法让绑定(bind)在 viewModel 中工作?

提前致谢。

最佳答案

将您的 ViewModel 放入您的 .Resources 并绑定(bind)到它?

<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。基本上您有两个数据源 - 一个在数据上下文中,另一个在您的资源中。

编辑:如果需要,您可以切换两者,这并不重要。您可以在资源中拥有任意数量的数据源。

关于c# - WPF ComboBox XML 绑定(bind)和 ViewModel 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4973762/

相关文章:

c# - 以编程方式将列和行添加到 WPF Datagrid

c# - 为什么 TreeView 控件不绑定(bind)

c# - 为什么选择 RelayCommand

c# - 如何模拟一个只读属性,其值取决于 Mock 的另一个属性

c# - WPF 单实例最佳实践

.net - 使用 WriteValue 手动绑定(bind)数据

grails - Grails Controller 操作中的多个域类绑定(bind)

c# - 反射 - 将对象转换到接口(interface)<interface>

c# - WPF UIElement 刷新错误?

c# - 获取WPF中单击的矩形的名称