我有一个示例mvvm应用程序。 UI具有文本框,按钮和组合框。当我在文本框中输入内容并点击按钮时,我输入的文本被添加到observablecollection中。 Combobox与该系列绑定。如何让组合框自动显示新添加的字符串?
答案 0 :(得分:5)
据我所知,你想要添加一个项目并选择它。 以下是使用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();
因此,在将添加的项目添加到集合后,必须将其添加为已选中。
因为OnItemsChanged
类的方法ComboBox
受到保护且无法使用。
答案 1 :(得分:3)
如果ComboBox绑定到ObservableCollection,则会在更改集合后立即更新ComboBox。
这是使用ObservableCollection的优势 - 您不需要进行任何额外的编码来更新UI。
如果这不是您所看到的行为,也许您可以发布一些代码/ xaml。