[英]WPF - Auto refresh combobox content
我有一個示例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
方法受到保護而無法使用。
如果ComboBox綁定到ObservableCollection,則ComboBox將在更改集合后立即更新。
這是使用ObservableCollection的優勢 - 您不需要進行任何額外的編碼來更新UI。
如果這不是您所看到的行為,也許您可以發布一些代碼/ xaml。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.