WPF一个依赖属性集合,通过选择不同的索引,绑定另多个集合中的一个集合
时间: 2024-03-09 14:46:09 浏览: 151
可以通过以下步骤实现:
1. 在WPF中创建一个依赖属性集合,例如:
```
public static readonly DependencyProperty OptionsProperty =
DependencyProperty.Register("Options", typeof(ObservableCollection<string>), typeof(YourControl), new PropertyMetadata(new ObservableCollection<string>()));
public ObservableCollection<string> Options
{
get { return (ObservableCollection<string>)GetValue(OptionsProperty); }
set { SetValue(OptionsProperty, value); }
}
```
2. 创建另外两个集合,例如Items1和Items2,并为它们添加数据。
3. 在XAML中,使用ComboBox来选择Options集合中的索引,例如:
```
<ComboBox ItemsSource="{Binding Options}" SelectedIndex="{Binding SelectedIndex}"/>
```
4. 在ViewModel中创建一个SelectedIndex属性,用于绑定ComboBox的SelectedIndex属性,并在SelectedIndex属性的setter方法中设置Items1或Items2集合,例如:
```
private int _selectedIndex;
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
_selectedIndex = value;
if (_selectedIndex == 0)
{
YourCollection = Items1;
}
else if (_selectedIndex == 1)
{
YourCollection = Items2;
}
OnPropertyChanged(nameof(SelectedIndex));
}
}
```
5. 在XAML中,使用ListBox来显示YourCollection集合中的数据,例如:
```
<ListBox ItemsSource="{Binding YourCollection}"/>
```
这样,当选择ComboBox中的不同索引时,ListBox中显示的数据就会自动切换为对应的集合中的数据。
阅读全文
相关推荐















