WPF,双向绑定到一个哈希表 [英] WPF, two-way binding to a hash table

查看:206
本文介绍了WPF,双向绑定到一个哈希表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绑定到数据表中的哈希表的值,并且值显示正常,但是当我在文本框中进行更改时,这些更改不会保留到对象。任何想法为什么这是?

I am binding to the values of a hash table from within a datatemplate and the values display fine, but the changes are not persisted to the object when I make changes in a text box for example. Any idea why this is?

   <DataTemplate x:Key="ResponseItemTemplate">
        <StackPanel Orientation="Horizontal" >
            <TextBox Width="200" Text="{Binding Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </StackPanel>
    </DataTemplate>

感谢您的时间

推荐答案

这不行,因为您使用的是不支持INotifyPropertyChanged的Hashtable。而不是绑定到哈希表,您应该绑定到一个ObservableCollection,它将处理您的所有更改通知。如果有类似哈希表的行为是必须的,您可以简单地扩展ObservableCollection并覆盖InsertItem和SetItem方法。这是一个例子:

This will not work because you are using a Hashtable, which does not support INotifyPropertyChanged. Instead of binding to a hash table, you should bind to an ObservableCollection, which will handle all of the change notification for you. If hashtable-like behavior is a must, you can simply extend ObservableCollection and override the InsertItem and SetItem methods. Here is an example of that:

public class SetCollection<T> : ObservableCollection<T> 
{
   protected override void InsertItem(int index, T item)
   {
      if (Contains(item))
         throw new ItemExistsException(item);

      base.InsertItem(index, item);
   }

   protected override void SetItem(int index, T item)
   {
      int i = IndexOf(item);
      if (i >= 0 && i != index)
         throw new ItemExistsException(item);

      base.SetItem(index, item);
   }
}

这篇关于WPF,双向绑定到一个哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆