0

I'm working with COM object provided by Activator.

It also provide events when properties is changed there but my PropertyGrid can't update them in-time because it comes from another thread and I'm getting :

A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

How to automate invoking property update when internal onChange is caused by external thread?

possible fix is: CheckForIllegalCrossThreadCalls = false;

But is it possible to handle this situation in proper way?

4

1 回答 1

1

假设您将对象绑定到 PropertyGrid,每当对象的属性发生更改时,它应该在 GUI 线程中触发 PropertyChanged 事件,以便 PropertyGrid 正确更新。

将 Property setter 编组到 GUI 线程是您的职责。如果您可以链接到任何控件,请使用该控件进行调用。否则,一般的解决方案是在开始时创建一个虚拟控件并将其用于调用。

public partial class ControlBase : UserControl
{
    /// <summary>
    /// Dummy control, use for invoking
    /// </summary>
    public static Control sDummyControl = null;

    /// <summary>
    /// Constructor
    /// </summary>
    public ControlBase()
    {
        InitializeComponent();

        if (sDummyControl == null)
        {
            sDummyControl = new Control();
            sDummyControl.Handle.ToString(); // Force create handle
        }
    }
}

在您的父对象中:

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (PropertyChanged == null)
        {
            return;
        }
        Control c = ControlBase.sDummyControl;
        if (c == null)
        {
            PropertyChanged(sender, e);
        }
        else
        {
            if (c.InvokeRequired)
            {
                c.BeginInvoke(new PropertyChangedEventHandler(RaisePropertyChanged), new object[] { sender, e });
            }
            else
            {
                PropertyChanged(sender, e);
            }
        }
    }

在您的对象中:

    public string Name
    {
        get { return _name; }
        set { _name = value; RaisePropertyChanged(this, new PropertyChangedEventArgs("Name")); }
    }

HTH,胡伊

于 2013-08-09T06:53:20.040 回答