2010-11-30 84 views
0

我有一个ListView绑定到一个LINQ to SQL对象。当我双击ListView中的文章时,它会打开文章详细信息窗口并允许用户更改文章属性。LINQ绑定刷新问题

到目前为止,它一切正常,但当用户保存并关闭文章详细信息时,ListView并不反映所做的更改(例如文章的描述)。我不想在所有的LINQ类中实现INotifyPropertyChanged,因为我使用VS2010来生成我的Linq表模式,因此改变自动生成的设计器代码是一件很痛苦的事情......(并且它肯定会覆盖我每次更改的所有更改我将对表的模式进行更改)

如何在简介窗口关闭时简单强制ListView刷新LINQ绑定?

提前感谢您的帮助。

回答

1

所有的Linq类都是以部分类的形式生成的 - 这意味着您可以创建自己的与Linq类匹配的分类,并添加所需的任何额外功能。然后当它被编译时,它将作为一个类来工作。

+0

我没注意到^^谢谢 – Karnalta 2010-11-30 10:55:47

1

一个快速简便的解决方案是使用一个DynamicObject装饰增添了变化notificcation行为,而无需改变你原来的班,或写一套房的部分类定义

public class DynamicBindingProxy<T> : DynamicObject, INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    private static readonly Dictionary<string, Dictionary<string, 
     PropertyInfo>> properties = new Dictionary<string, 
      Dictionary<string, PropertyInfo>>(); 
    private readonly T instance; 
    private readonly string typeName; 

    public DynamicBindingProxy(T instance) 
    { 
     this.instance = instance; 
     var type = typeof(T); 
     typeName = type.FullName; 
     if (!properties.ContainsKey(typeName)) 
      SetProperties(type, typeName); 
    } 

    private static void SetProperties(Type type, string typeName) 
    { 
     var props = type.GetProperties(
      BindingFlags.Public | BindingFlags.Instance); 
     var dict = props.ToDictionary(prop => prop.Name); 
     properties.Add(typeName, dict); 
    } 

    public override bool TryGetMember(GetMemberBinder binder, 
     out object result) 
    { 
     if (properties[typeName].ContainsKey(binder.Name)) 
     { 
      result = properties[typeName][binder.Name] 
       .GetValue(instance, null); 
      return true; 
     } 
     result = null; 
     return false; 
    } 

    public override bool TrySetMember(SetMemberBinder binder, 
     object value) 
    { 
     if (properties[typeName].ContainsKey(binder.Name)) 
     { 
      properties[typeName][binder.Name] 
       .SetValue(instance, value, null); 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(binder.Name)); 
      return true; 
     } 
     return false; 
    } 
} 

和继承人的样本用途:

public partial class MainWindow : Window 
{ 
    private readonly TestObj tObj; 
    private DynamicBindingProxy<TestObj> dynObj; 
    public MainWindow() 
    { 
     InitializeComponent(); 
     tObj = new TestObj() { Name = "test", Amount = 123.45, ID = 44, SomeDate = DateTime.Now }; 
     dynObj = new DynamicBindingProxy<TestObj>(tObj); 
     DataContext = dynObj; 
    } 

    private void UpdateName(object sender, RoutedEventArgs e) 
    { 
     ((dynamic)dynObj).Name = newText.Text; 
    } 
} 

全部细节可以在博客文章中,我专门写这个被发现的问题 http://www.deanchalk.me.uk/post/WPF-e28093-Easy-INotifyPropertyChanged-Via-DynamicObject-Proxy.aspx