gpt4 book ai didi

wpf - 需要一个使用 MVVM 级联组合框的简单示例

转载 作者:行者123 更新时间:2023-12-03 10:52:18 25 4
gpt4 key购买 nike

需要一个使用 MVVM 级联组合框的简单示例

Wpf/Silverlight

最佳答案

如果我理解您的问题,您希望下一个组合框根据前一个值填充数据。

我有一个通用的 ViewModel,您必须捕获项目列表和所选项目

class ItemListViewModel<T> : INotifyPropertyChanged where T : class
{
private T _item;
private ObservableCollection<T> _items;

public ItemListViewModel()
{
_items = new ObservableCollection<T>();
_item = null;
}

public void SetItems(IEnumerable<T> items)
{
Items = new ObservableCollection<T>(items);
SelectedItem = null;
}

public ObservableCollection<T> Items
{
get { return _items; }
private set
{
_items = value;
RaisePropertyChanged("Items");
}
}

public T SelectedItem
{
get { return _item; }
set
{
_item = value;
RaisePropertyChanged("SelectedItem");
}
}

public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

然后拥有将绑定(bind)到 View 的 DataContext 的主视图模型。让 Load 方法做你想做的事
class MyViewModel : INotifyPropertyChanged
{
public MyViewModel()
{
First = new ItemListViewModel<string>();
Second = new ItemListViewModel<string>();
Third = new ItemListViewModel<string>();

First.PropertyChanged += (s, e) => Update(e.PropertyName, First, Second, LoadSecond);
Second.PropertyChanged += (s, e) => Update(e.PropertyName, Second, Third, LoadThird);

LoadFirst();
}

public ItemListViewModel<string> First { get; set; }
public ItemListViewModel<string> Second { get; set; }
public ItemListViewModel<string> Third { get; set; }

private void LoadFirst()
{
First.SetItems(new List<string> { "One", "Two", "Three" });
}
private void LoadSecond()
{
Second.SetItems(new List<string> { "First", "Second", "Third" });
}
private void LoadThird()
{
Third.SetItems(new List<string> { "Firsty", "Secondly", "Thirdly" });
}

private void Update<T0, T1>(string propertyName, ItemListViewModel<T0> parent, ItemListViewModel<T1> child, Action loadAction)
where T0 : class
where T1 : class
{
if (propertyName == "SelectedItem")
{
if (parent.SelectedItem == null)
{
child.SetItems(Enumerable.Empty<T1>());
}
else
{
loadAction();
}
}
}

public event PropertyChangedEventHandler PropertyChanged;
}

在您看来,此代码在某处。
    <ComboBox ItemsSource="{Binding First.Items}" SelectedItem="{Binding First.SelectedItem}" />
<ComboBox ItemsSource="{Binding Second.Items}" SelectedItem="{Binding Second.SelectedItem}" />
<ComboBox ItemsSource="{Binding Third.Items}" SelectedItem="{Binding Third.SelectedItem}" />

您可以重构以使其更好,使用 MVVM 框架或专门为项目列表派生 ItemListViewModel 并在那里加载负载以更好地封装。由你决定。

如果任何父组合框值发生更改,则所有子列表都将被清除。

高温高压

关于wpf - 需要一个使用 MVVM 级联组合框的简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3677098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com