用C#代码怎么实现WPF中实现不同页面相同ComboBox控件绑定数据源数据的同步
时间: 2023-12-24 17:05:55 浏览: 83
学生作业 C#实例源码 美化ComboBox.rar
好的,以下是用C#代码实现WPF中实现不同页面相同ComboBox控件绑定数据源数据的同步的方法:
1. 首先,创建一个ViewModel类,并在其中定义ComboBox的数据源和选中项属性,同时实现INotifyPropertyChanged接口,如下所示:
```
public class MyViewModel : INotifyPropertyChanged
{
private ObservableCollection<string> _itemsSource;
private string _selectedItem;
public ObservableCollection<string> ItemsSource
{
get { return _itemsSource; }
set
{
_itemsSource = value;
OnPropertyChanged("ItemsSource");
}
}
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
2. 在每个页面的代码中,创建一个MyViewModel实例,并将ComboBox的ItemsSource和SelectedValue属性分别绑定到ViewModel中对应的属性,如下所示:
```
public partial class Page1 : Page
{
private MyViewModel _viewModel;
public Page1()
{
InitializeComponent();
_viewModel = MyViewModel.Instance;
comboBox1.ItemsSource = _viewModel.ItemsSource;
comboBox1.SetBinding(ComboBox.SelectedValueProperty, new Binding("SelectedItem") { Mode = BindingMode.TwoWay });
}
}
public partial class Page2 : Page
{
private MyViewModel _viewModel;
public Page2()
{
InitializeComponent();
_viewModel = MyViewModel.Instance;
comboBox1.ItemsSource = _viewModel.ItemsSource;
comboBox1.SetBinding(ComboBox.SelectedValueProperty, new Binding("SelectedItem") { Mode = BindingMode.TwoWay });
}
}
```
3. 在MyViewModel类中使用Singleton模式创建一个实例,确保所有页面使用的是同一个ViewModel对象,如下所示:
```
public class MyViewModel : INotifyPropertyChanged
{
private static MyViewModel _instance;
private ObservableCollection<string> _itemsSource;
private string _selectedItem;
public static MyViewModel Instance
{
get
{
if (_instance == null)
{
_instance = new MyViewModel();
}
return _instance;
}
}
public ObservableCollection<string> ItemsSource
{
get { return _itemsSource; }
set
{
_itemsSource = value;
OnPropertyChanged("ItemsSource");
}
}
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
这样就可以在不同页面中实现ComboBox控件绑定数据源数据的同步了。需要注意的是,要确保ViewModel的生命周期和页面的生命周期一致,否则可能会出现数据同步不成功的情况。
阅读全文