【问题标题】:Using ObservableCollection<Dictionary<String, Object>> as DataGrid Itemsource in WPF使用 ObservableCollection<Dictionary<String, Object>> 在 WPF 中有 DataGrid Itemssource
【发布时间】:2017-06-21 02:05:08
【问题描述】:

我有一个DataGrid 并且我设置ItemsSource 是一个ObservableCollection&lt;Dictionary&lt;String, object&gt;&gt; 对象。

通常,我只定义一个ClassA并将ObservableCollection&lt;ClassA&gt;设置为ItemsSource,然后我可以将属性名称绑定到ClassA的列(DataGridTextColumn)。

但我不知道如何绑定字典的键/值。

有什么支持吗?

【问题讨论】:

  • 你必须在泛型周围加上尖括号,否则浏览器会认为它们是标签并吞下它们。请在提交后阅读您的问题,这样您会发现类似的错误。在我为您解决之前,您的问题毫无意义。

标签: c# wpf xaml mvvm


【解决方案1】:

你的问题相当复杂,为了创建ObservableDictionary&lt;TKey, TValue&gt;,应该创建一个实现的类:

IDictionary
INotifyCollectionChanged
INotifyPropertyChanged 
ICollection<KeyValuePair<TKey,TValue>>
IEnumerable<KeyValuePair<TKey,TValue>>
IEnumerable

接口。 More in depth 在这里。这种实现的一个例子是:

class ObservableDictionary<TKey, TValue> : IDictionary, INotifyCollectionChanged, INotifyPropertyChanged
{
    private Dictionary<TKey, TValue> mDictionary;

    //Methods & Properties for IDictionary implementation would defer to mDictionary:
    public void Add(TKey key, TValue value)
    {
        mDictionary.Add(key, value);
        OnCollectionChanged(NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, value)
        return;
    }

    //Implementation of INotifyCollectionChanged:
    public event NotifyCollectionChangedEventHandler CollectionChanged;
    protected void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
    {
        //event fire implementation
    }

    //Implementation of INotifyProperyChanged:
    public event ProperyChangedEventHandler ProperyChanged;
    protected void OnPropertyChanged(PropertyChangedEventArgs args)
    {
        //event fire implementation
    }
}

另一种选择是 nice solution 的可绑定动态字典,它将每个字典条目作为属性公开。

public sealed class BindableDynamicDictionary : DynamicObject, INotifyPropertyChanged
{
    /// <summary>
    /// The internal dictionary.
    /// </summary>
    private readonly Dictionary<string, object> _dictionary;

    /// <summary>
    /// Creates a new BindableDynamicDictionary with an empty internal dictionary.
    /// </summary>
    public BindableDynamicDictionary()
    {
        _dictionary = new Dictionary<string, object>();
    }

    /// <summary>
    /// Copies the contents of the given dictionary to initilize the internal dictionary.
    /// </summary>
    public BindableDynamicDictionary(IDictionary<string, object> source)
    {
        _dictionary = new Dictionary<string, object>(source);
    }

    /// <summary>
    /// You can still use this as a dictionary.
    /// </summary>
    public object this[string key]
    {
        get { return _dictionary[key]; }
        set
        {
            _dictionary[key] = value;
            RaisePropertyChanged(key);
        }
    }

    /// <summary>
    /// This allows you to get properties dynamically.
    /// </summary>
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return _dictionary.TryGetValue(binder.Name, out result);
    }

    /// <summary>
    /// This allows you to set properties dynamically.
    /// </summary>
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        _dictionary[binder.Name] = value;
        RaisePropertyChanged(binder.Name);
        return true;
    }

    /// <summary>
    /// This is used to list the current dynamic members.
    /// </summary>
    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _dictionary.Keys;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propertyName)
    {
        var propChange = PropertyChanged;
        if (propChange == null) return;
        propChange(this, new PropertyChangedEventArgs(propertyName));
    }
}

那么你可以这样使用它:

private void testButton1_Click(object sender, RoutedEventArgs e)
{
    var dd = new BindableDynamicDictionary(); // Creating a dynamic dictionary.
    dd["Age"] = 32; //access like any dictionary

    dynamic person = dd; //or as a dynamic
    person.FirstName = "Alan"; // Adding new dynamic properties. The TrySetMember method is called.
    person.LastName = "Evans";

    //hacky for short example, should have a view model and use datacontext
    var collection = new ObservableCollection<object>();
    collection.Add(person);
    dataGrid1.ItemsSource = collection;
}

Datagrid 需要自定义代码来构建列:

XAML:

<DataGrid AutoGenerateColumns="True" Name="dataGrid1" AutoGeneratedColumns="dataGrid1_AutoGeneratedColumns" />

AutoGeneratedColumns 事件:

private void dataGrid1_AutoGeneratedColumns(object sender, EventArgs e)
{
    var dg = sender as DataGrid;
    var first = dg.ItemsSource.Cast<object>().FirstOrDefault() as DynamicObject;
    if (first == null) return;
    var names = first.GetDynamicMemberNames();
    foreach(var name in names)
    {
        dg.Columns.Add(new DataGridTextColumn { Header = name, Binding = new Binding(name) });            
    }            
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-09
    • 2012-03-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2014-10-05
    相关资源
    最近更新 更多