WPF ComboBox XML binding and ViewModel binding?

I have an XML file with a list of countries. I am using XMLDataProvider in xaml to bind the Items_SourceBox element. I also have a viewModel with the property to which I wanted to bind the selected value. I tried binding to viewmodel using local namespace:

SelectedValuePath="Country"

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

However, I had to use a DataContext for xmlProvider.

Is there a way to make binding work in viewModel?

Thanks in advance.

+4
source share
2 answers

Put your ViewModel in your .Resources and bind to it?

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

NTN. Basically, you have two data sources: one in the datacontext, and the other in your resources.

EDIT: you can switch two if necessary, it doesn't really matter. Your resources can have as many data sources as you like.

0
source

If your ViewModel is a public view property, you can name your view and access it that way.

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

... or something like that.

0
source

Source: https://habr.com/ru/post/1339406/


All Articles