我有一个ComboBox cbo1
。
我试图使用ViewModel
和CollectionChanged
来更改项源,但是ComboBox项仍然是空白的,不会更新。
我在这里尝试过几个例子和解决方案,但不知道如何正确地实现它们。
XAML
<ComboBox x:Name="cbo1"
ItemsSource="{Binding cbo1_Items, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding cbo1_SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Margin="0,0,0,0"
VerticalAlignment="Top"
Width="105"
Height="22" />
ViewModelBase类
绑定ComboBox项
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public ViewModelBase()
{
_cbo1_Items = new ObservableCollection<string>();
_cbo1_Items.CollectionChanged += cbo1_Items_CollectionChanged;
}
// Notify Collection Changed
//
public void cbo1_Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Notify("cbo1_Items");
}
// Item Source
//
public static ObservableCollection<string> _cbo1_Items = new ObservableCollection<string>();
public static ObservableCollection<string> cbo1_Items
{
get { return _cbo1_Items; }
set { _cbo1_Items = value; }
}
// Selected Item
//
public static string cbo1_SelectedItem { get; set; }
}
示例类
在这个类中,我希望更改ComboBox项源。
// Change ViewModel Item Source
//
ViewModelBase._cbo1_Items = new ObservableCollection<string>()
{
"Item 1",
"Item 2",
"Item 3"
};
// ...
// Change Item Source Again
//
ViewModelBase._cbo1_Items = new ObservableCollection<string>()
{
"Item 4",
"Item 5",
"Item 6"
};
发布于 2018-07-14 10:39:58
在属性声明中实现- RaisePropertyChanged("ComboBoxItemsource");/NotifyPropertyChanged("ComboBoxItemsource")。例:-
观照
<ComboBox Width="40" Height="40" ItemsSource="{Binding ComboBoxItemsource, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
在视图模型中-
private ObservableCollection<string> comboBoxItemsource;
public ObservableCollection<string> ComboBoxItemsource
{
get { return comboBoxItemsource; }
set
{
if (comboBoxItemsource != value)
{
comboBoxItemsource = value;
RaisePropertyChanged("ComboBoxItemsource");
}
}
}
In Class Constructor-
public ClassViewModel()
{
ComboBoxItemsource = new ObservableCollection<string>();
ComboBoxItemsource.Add("Item1");
ComboBoxItemsource.Add("Item2");
....
}
//Event on which you want to change the collection
public void OnClickEvent()
{
ComboBoxItemsource = new ObservableCollection<string>();
ComboBoxItemsource.Add("Item5");
ComboBoxItemsource.Add("Item6");
}
类应该继承和实现INotifyPropertyChanged。希望这有帮助..。
https://stackoverflow.com/questions/51336841
复制相似问题