4
votes

I have an XML file with a list of countries. I use an XMLDataProvider in xaml to bind a combobox's ItemsSource. I also have a viewModel with a property that I wanted to bind the selected value to. I've tried to bind to the viewmodel using a namespace local:

SelectedValuePath="Country"

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

However I had to se the DataContext for the xmlProvider.

Is there a way to get the binding to work in the viewModel?

Thanks in advance.

2
do you set your viewModel as DataContext or not ? - Snowbear

2 Answers

0
votes

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

<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. Basically you have two datasources - one in the datacontext and the other in your resources.

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.

0
votes

If your ViewModel is a public property of the view you could name your view and get access to it that way.

<Window Name="Window"
        ...>

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

...or something like that.