C# WPF-自动刷新组合框内容
我有一个mvvm应用程序示例。UI有一个文本框、一个按钮和一个组合框。当我在文本框中输入一些内容并按下按钮时,我输入的文本将被添加到observablecollection中。组合框已绑定到该集合。如何让combobox自动显示新添加的字符串?如果combobox绑定到一个ObservableCollection,则一旦集合发生更改,combobox将立即更新 这就是使用ObservableCollection的优点——您不需要做任何额外的编码来更新UIC# WPF-自动刷新组合框内容,c#,wpf,mvvm,combobox,auto-update,C#,Wpf,Mvvm,Combobox,Auto Update,我有一个mvvm应用程序示例。UI有一个文本框、一个按钮和一个组合框。当我在文本框中输入一些内容并按下按钮时,我输入的文本将被添加到observablecollection中。组合框已绑定到该集合。如何让combobox自动显示新添加的字符串?如果combobox绑定到一个ObservableCollection,则一旦集合发生更改,combobox将立即更新 这就是使用ObservableCollection的优点——您不需要做任何额外的编码来更新UI 如果这不是您看到的行为,也许您可以发布一
如果这不是您看到的行为,也许您可以发布一些代码/xaml。正如我正确理解的那样,您希望添加一个项目并选择它。 下面是如何使用ViewModel和绑定完成此操作的示例 Xaml: 因此,在将添加的项添加到集合后,必须将其显式设置为选中项 因为
组合框
类的方法OnItemChanged
受到保护,无法使用
<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)this.DataContext).AddNewItem();