在网格中使用2个不同的ViewModel

时间:2017-06-14 10:14:47

标签: c# wpf xaml mvvm

你可以在网格中使用2个不同的ViewModel吗?

一个ViewModel用于填充ComboBox,另一个ViewModel用于获取selectedItem?

喜欢这个样本(不工作):

<Grid Grid.Row="4"
      DataContext="{Binding ViewModel1, Mode=OneWay, Source={StaticResource Locator}}">
    <TextBlock Grid.Row="4"
            Text="Language:"
            FontWeight="Bold"
            VerticalAlignment="Center" />
    <ComboBox Grid.Column="1"
            DisplayMemberPath="Value"
            VerticalAlignment="Center"
            Width="200"
            ItemsSource="{Binding LanguageList}"
            DataContext="{Binding ViewModel2, Mode=OneWay, Source={StaticResource Locator}}"
            SelectedItem="{Binding SelectedLanguage}"/>
</Grid>

1 个答案:

答案 0 :(得分:1)

您可以为每个绑定指定显式来源:

<Grid Grid.Row="4">
    <TextBlock Grid.Row="4"
                Text="Language:"
                FontWeight="Bold"
                VerticalAlignment="Center" />
    <ComboBox Grid.Column="1"
                DisplayMemberPath="Value"
                VerticalAlignment="Center"
                Width="200"
                ItemsSource="{Binding ViewModel1.LanguageList, Source={StaticResource Locator}}"
                SelectedItem="{Binding ViewModel2.SelectedLanguage, Source={StaticResource Locator}}"/>
</Grid>
相关问题