我正在学习WPF MVVM,并且一直在努力解决我认为很简单的问题,但是自己无法解决。
我的目标是能够在已填充的ComboBox中选择一个项目,然后根据该选择填充另一个ComboBox。我似乎无法在选择后加载第二个ComboBox。
我已经包含了一个具有2个ComboBox和1个TextBlock的示例。当我运行应用程序并在第一个ComboBox中选择一个项目时,基于绑定,TextBlock会更新,但是我不知道在哪里调用代码以更新第二个ComboBox。
我尝试将调用添加到SelectedString属性setter中,但是那似乎从未被调用过。我肯定错过了什么简单的东西,但我需要有人帮助我揭开谜团!
我已经尝试了其他帖子上的建议,但到目前为止还没有成功。
以下是视图的XAML:
我的目标是能够在已填充的ComboBox中选择一个项目,然后根据该选择填充另一个ComboBox。我似乎无法在选择后加载第二个ComboBox。
我已经包含了一个具有2个ComboBox和1个TextBlock的示例。当我运行应用程序并在第一个ComboBox中选择一个项目时,基于绑定,TextBlock会更新,但是我不知道在哪里调用代码以更新第二个ComboBox。
我尝试将调用添加到SelectedString属性setter中,但是那似乎从未被调用过。我肯定错过了什么简单的东西,但我需要有人帮助我揭开谜团!
我已经尝试了其他帖子上的建议,但到目前为止还没有成功。
以下是视图的XAML:
<Window x:Class="ThrowAwayMVVMApp.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="400" Width="800">
<DockPanel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60*" />
<RowDefinition Height="282*" />
</Grid.RowDefinitions>
<!-- Add additional content here -->
<ComboBox ItemsSource="{Binding MyStrings}" SelectedItem="{Binding Path=SelectedString, Mode=TwoWay}" Height="23" HorizontalAlignment="Left" Margin="18,24,0,0" Name="comboBox1" VerticalAlignment="Top" Width="204" />
<TextBlock Text="{Binding SelectedString}" Height="23" HorizontalAlignment="Left" Margin="276,24,0,0" Name="textBlock1" VerticalAlignment="Top" Width="227" Background="#FFFAE7E7" />
<ComboBox ItemsSource="{Binding ResultStrings}" Height="23" HorizontalAlignment="Left" Margin="543,25,0,0" Name="comboBox2" VerticalAlignment="Top" Width="189" />
</Grid>
</DockPanel>
</Window>
这是视图模型:
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
this.MyStrings = new ObservableCollection<string>
{
"One",
"Two",
"Three",
"Four",
"Five"
};
}
public ObservableCollection<string> MyStrings { get; set; }
public ObservableCollection<string> ResultStrings { get; set; }
public string SelectedString
{
get { return (string)GetValue(SelectedStringProperty); }
set
{
SetValue(SelectedStringProperty, value);
this.ResultStrings = getResultStrings(value);
}
}
// Using a DependencyProperty as the backing store for SelectedString. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedStringProperty =
DependencyProperty.Register("SelectedString", typeof(string), typeof(MainViewModel), new UIPropertyMetadata(""));
private ObservableCollection<string> getResultStrings(string input)
{
ObservableCollection<string> result = null;
if (input == "Three")
{
result = new ObservableCollection<string> { "Six", "Seven", "Eight" };
}
else
{
result = new ObservableCollection<string> { "Nine", "Ten", "Eleven" };
}
return result;
}
}