开发者

Exception when trying to add Controls to a UserControl

While I was trying to add Controls to my UserControl list it t开发者_运维技巧hrew "The calling thread cannot access this object because a different thread owns it." exception.

        panel_PanelHolder.Children.Clear();
        panel_PanelHolder.Children.Add(usr_panel);

But when I used below code,

        Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
        {
            panel_PanelHolder.Children.Clear();
            panel_PanelHolder.Children.Add(usr_panel);
        }));

It throws "Exception has been thrown by the target of an invocation." exception.

What I need is to clear controls, and add a control to the panel. I'm not sure how to fix this ASAP. I'm using a STA thread to manipulate WPF window controls dynamically. Can someone help me on this? thx..


I had this problem today. Using a debugger, you need to dig into the exception tree. For each exception, there may be an inner exception. Dig as deep as possible. Then look at the stack trace. In my case, I had a (custom) user control that, during construction, caused a null ref exception.

Your case may be less obvious. Look at stacktrace of the deepest exception, then set a breakpoint at that line of code. If further debugging does not reveal the issue, try to surround the offending line of code with a try..catch block. Then you can poke at the exception more locally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜