gpt4 book ai didi

c# - 将项目添加到未知类型的 ObservableCollection

转载 作者:行者123 更新时间:2023-12-03 10:30:57 24 4
gpt4 key购买 nike

我正在使用 MVVM 设计模式创建一个 WPF 应用程序,并且我正在尝试创建一个允许用户在运行时编辑下拉列表中的项目的组合框,类似于 MS Access 2007 让你这样做的方式.所以我创建了一个建立在组合框之上的用户控件......当显示下拉列表时,列表下方有一个按钮,可以打开另一个窗口来编辑列表中的项目。非常简单,但弹出窗口对列表中的项目类型一无所知,除了它们属于某种类型的 ObservableCollection。

您可以查看我要解释的内容的屏幕截图 HERE .

例如,在 View 上,我将自定义组合框绑定(bind)到 ObservableCollection<Sizes> .我单击按钮编辑列表,弹出窗口显示 TextBox 中的所有项目供用户编辑。问题是尝试从弹出窗口中添加/更新/删除 ObservableCollection 中的项目。除了显示字段的名称 (this.DisplayMemberPath) 之外,此窗口不知道有关 ObservableCollection 的任何信息。

我知道我总是可以将组合框绑定(bind)到 ObservableCollection<string> , 或 IEnumerable<string> ,但我使用 LINQ to SQL 来填充组合框项目,并且我需要了解对所有对象的更改跟踪,以便更新对列表所做更改的数据库。因此,(我认为)我必须使用 ObservableCollection<Sizes>以监控更改跟踪。我也玩过使用 CollectionChanged 事件来更新数据库的想法,但我想知道是否有更清洁的方法。

我有一种感觉,我需要使用 Reflection 来更新列表,但我不太精通使用 Reflection。

这是我用于显示弹出窗口的源代码:

public event EventHandler<EventArgs> EditListClick;
private void EditButton_Click(object sender, RoutedEventArgs e)
{
if (this.EditListDialog == null)
{
// Create the default dialog window for editing the list
EditListDialogWindow dialog = new EditListDialogWindow();
string items = string.Empty;

if (this.Items != null)
{
// Loop through each item and flatten the list
foreach (object item in this.Items)
{
PropertyInfo pi = item.GetType().GetProperty(this.DisplayMemberPath);
string value = pi.GetValue(item, null) as string;

items = string.Concat(items, ((items == string.Empty) ? items : "\n") + value);
}

// Now pass the information to the dialog window
dialog.TextList = items;
}

// Set the owner and display the dialog
dialog.Owner = Window.GetWindow(this);
dialog.ShowDialog();

// If the user has pressed the OK button...
if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
{
// Make sure there has been a change
if (items != dialog.TextList)
{
// Unflatten the string into an Array
string[] itemArray = dialog.TextList.Split(new string[]{"\n", "\r"}, StringSplitOptions.RemoveEmptyEntries);

// Add the items to the list
foreach (string item in itemArray)
{
// This is where I run into problems...
// Should I be using reflection here??
((ObservableCollection<object>)this.ItemsSource).Add(item.Trim());
}
}
}
}

if (EditListClick != null)
EditListClick(this, EventArgs.Empty);
}

最佳答案

听起来您需要了解列表,但不需要了解具体类型。这就是非通用接口(interface)的用武之地;尝试以 IList 的身份访问列表(具有所有索引器/添加/删除等),INotifyCollectionChanged (用于通知)等

在更一般的情况下,还有 IBindingList/IBindingListView/ITypedList等,但我认为在这种情况下你不需要这些。

关于c# - 将项目添加到未知类型的 ObservableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2040474/

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