c# – WPF – 自动刷新组合框内容
发布时间:2020-12-15 08:29:13 所属栏目:百科 来源:网络整理
导读:我有一个示例mvvm应用程序. UI具有文本框,按钮和组合框.当我在文本框中输入内容并点击按钮时,我输入的文本被添加到observablecollection中. Combobox与该系列绑定.如何让组合框自动显示新添加的字符串? 解决方法 据我所知,你想添加一个项目并选择它. 以下是
我有一个示例mvvm应用程序. UI具有文本框,按钮和组合框.当我在文本框中输入内容并点击按钮时,我输入的文本被添加到observablecollection中. Combobox与该系列绑定.如何让组合框自动显示新添加的字符串?
解决方法
据我所知,你想添加一个项目并选择它.
以下是使用ViewModel和绑定如何完成的示例. XAML: <StackPanel> <TextBox Text="{Binding ItemToAdd}"/> <ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" /> <Button Content="Add" Click="Button_Click"/> </StackPanel> 视图模型: public class MainViewModel:INotifyPropertyChanged { public ObservableCollection<string> Items { get; set; } public string ItemToAdd { get; set; } private string selectedItem; public string SelectedItem { get { return selectedItem; } set { selectedItem = value; OnPropertyChanged("SelectedItem"); } } public void AddNewItem() { this.Items.Add(this.ItemToAdd); this.SelectedItem = this.ItemToAdd; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this,new PropertyChangedEventArgs(propertyName)); } } } MainViewModel有3个属性(一个用于TextBox,另外两个用于ComboBox)和方法AddNewItem不带参数. 该方法可以从命令触发,但命令没有标准类,所以我将从代码隐藏中调用它: ((MainViewModel)this.DataContext).AddNewItem(); 因此,在将其添加到集合后,必须将添加的项明确设置为已选中. 因为ComboBox类的OnItemsChanged方法受到保护而无法使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |