[英]WPF - Can't set combobox selectedIndex when itemssource changes
我有一個顯示項目列表的組合框。 顯示的項目列表由一組單選按鈕確定。 我將單擊事件附加到單選按鈕,並嘗試在組合框上設置新的項源。 我希望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));
}
}
}
您的XAML中沒有對ComboBoxViewModel
視圖模型的任何數據綁定,至少提供了一個。 我認為這就是問題所在。
您需要將組合框綁定到VM。
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();
cb_Test.DataContext = viewModel;
}
private void radioButton1_Click(object sender, RoutedEventArgs e)
{
viewModel.ItemsSource = list1;
viewModel.SelectedIndex = 0;
}
private void radioButton2_Click(object sender, RoutedEventArgs e)
{
viewModel.ItemsSource = list2;
viewModel.SelectedIndex = 0;
}
}
在XAML中
<Grid>
<ComboBox Name="cb_Test"
ItemsSource="{Binding ItemsSourse}"
SelectedIndex="{Binding SelectedIndex}"/>
<RadioButton Content="List 1" Name="radioButton1" Click="radioButton1_Click" />
<RadioButton Content="List 2" Name="radioButton2" Click="radioButton2_Click" />
</Grid>
更好的設計是移動代碼viewModel.ItemsSource = list1; viewModel.SelectedIndex = 0;
viewModel.ItemsSource = list1; viewModel.SelectedIndex = 0;
虛擬機本身。
同意提格倫。 無論這是什么,都需要將ComboBoxViewModel分配為Window / Page / Control的DataContext,並且需要在xaml的ComboBox的聲明中綁定SelectedIndex。 由於需要綁定,因此還應該將List集合移動到具有SelectedIndex的一個ViewModel,並將ComboBox ItemsSource綁定到ViewModel中的一個屬性,該屬性可以在某些條件下設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.