2011-02-11 34 views
4

我有一個國家列表的XML文件。我在xaml中使用XMLDataProvider來綁定組合框的ItemsSource。我也有一個viewModel的屬性,我想綁定選定的值。我試圖綁定使用命名空間的本地視圖模型:WPF組合框XML綁定和ViewModel綁定?

SelectedValuePath="Country"

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

但是我不得不瑟在DataContext的xmlProvider。

有沒有辦法讓綁定在viewModel中工作?

在此先感謝。

+0

您是否將您的viewModel設置爲DataContext或不? – Snowbear

回答

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中,另一個在你的資源中。

編輯:你可以切換兩個如果需要的話,它並不重要。您可以在資源中擁有儘可能多的數據源。

+0

工作完美,謝謝!試圖upvote你的評論,don – jeremywho

+0

@jeremywho:既然這個工作,你應該可以接受它作爲答案,通過點擊下方左邊的複選標記輪廓。 –

0

如果您的ViewModel是視圖的公共屬性,您可以命名您的視圖並以此方式訪問它。

<Window Name="Window" 
     ...> 

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

...或類似的東西。