【发布时间】:2011-08-01 19:32:01
【问题描述】:
我有一个显示项目列表的组合框。显示的项目列表由一组单选按钮确定。我附加到单选按钮单击事件并尝试在组合框上设置新的 itemssource。我希望 selectedItem 默认为 0,而不是 -1。
我做错了什么?
<Grid>
<ComboBox Name="cb_Test" />
<RadioButton Content="List 1" Name="radioButton1" Click="radioButton1_Click" />
<RadioButton Content="List 2" Name="radioButton2" Click="radioButton2_Click" />
</Grid>
public partial class MainWindow : Window
{
List<string> list1 = new List<string>() { "list 1", "list 1", "list 1" };
List<string> list2 = new List<string>() { "list 2", "list 2", "list 2" };
ComboBoxViewModel viewModel = new ComboBoxViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = viewModel;
cb_Test.ItemsSource = list1;
}
private void radioButton1_Click(object sender, RoutedEventArgs e)
{
cb_Test.ItemsSource = list1;
viewModel.SelectedIndex = 0;
}
private void radioButton2_Click(object sender, RoutedEventArgs e)
{
cb_Test.ItemsSource = list2;
viewModel.SelectedIndex = 0;
}
}
public class ComboBoxViewModel : INotifyPropertyChanged
{
private int selectedIndex;
public event PropertyChangedEventHandler PropertyChanged;
public int SelectedIndex
{
get { return selectedIndex; }
set
{
if (selectedIndex != value)
{
selectedIndex = value;
NotifyPropertyChanged("SelectedIndex");
}
}
}
private void NotifyPropertyChanged(string controlName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(controlName));
}
}
}
【问题讨论】:
-
您的视图模型似乎没有绑定到组合框,对吧?
标签: c# wpf combobox itemssource selectedindex