我有一個ComboBox
它綁定到在ViewModel中定義的List<String>
。 我也有ListBox
誰是ItemSource取決於SelectedValue
從ComboBox
。綁定ListBos ItemSource到Combobox的selectedVAlue
在視圖模型,我具有以下性質:
List<String> ComboBoxSource
string SelectedValue
(ComboBox
選定值)ObservableCollection<String> ListBoxSource
現在,當ComboBox
selectedvalue
變化,我在ViewModel中設置SelectedVAlue
屬性( DataContext
)明確表示正在引發PropertyChange
事件ListBoxSource
以更新ListBox
。
我的問題是我怎麼能做到這一點沒有明確設置在視圖模型SelectedVAlue
即我能系ComboBox.SelectedVAlue
我SelectedVAlue
財產?
這是我的XAML:
<ComboBox Grid.Column="0" Grid.Row="0" x:Name="ComboBoxVersions" SelectedIndex="0" Margin="10" SelectionChanged="ComboBoxVersions_OnSelectionChanged" ItemsSource="{Binding EnvironmentVersions}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Version " />
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ListBox x:Name="ListBoxEnvironments" Grid.Column="0" Grid.Row="1" Height="300" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" Margin="10" SelectionMode="Multiple" ItemsSource="{Binding Environments}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" HorizontalAlignment="Left" Width="800" >
</WrapPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="CheckBoxEnvironment" Content="{Binding}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Margin="5">
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
這裏是後面的代碼:
/// <summary>
/// Handles the OnSelectionChanged event of the ComboBoxVersions control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="SelectionChangedEventArgs"/> instance containing the event data.</param>
private void ComboBoxVersions_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var dataContext = this.DataContext as TestRunnerControlViewModel;
dataContext.SelectedVersion = ((ComboBox) sender).SelectedValue.ToString();
}