我有一个问题。我想在一个用户控件中更新主UI。我尝试了很多次,但我没有成功。测试分为以下两类:
第一类:
我先是直接赋值主窗口控件(tbInfo,TextBlock类型),不成功。于是我创建了一个textBlockUpdate类(实现属性变化通知接口),并将其属性(TextMessage)绑定到tbInfo的Text属性上,不成功。然后我用了内容控件,也没有成功。代码如下:
//Feature code in user control.
info = string.Format("Adding file{0}", System.IO.Path.GetFileName(FileName));
if (_dataObject.MainWindow != null)
{
_dataObject.MainWindow.ShowInfo(info);
}
//Feature code in main window.
public void ShowInfo(string info)
{
if (Dispatcher.CheckAccess())
{
//tbInfo.Text = info;
// textBlockUpdate.TextMessage = info;
TextBlock textBlock = new TextBlock();
textBlock.Text = info;
tbInfoContainer.Content = textBlock;
}
else
{
Action<string> showInfoDel = (str) =>
{
// tbInfo.Text = info;
//textBlockUpdate.TextMessage = info;
TextBlock textBlock = new TextBlock();
textBlock.Text = info;
tbInfoContainer.Content = textBlock;
};
Dispatcher.BeginInvoke(showInfoDel, info);
}
}
第2类:我把用户控件中的代码放到一个线程中,还是没有成功。我试了3次,都没有成功。
1.
new Thread(()=>{
this.Dispatcher.Invoke(new Action(()=>{
//Add the feature code above here
}));
}).Start();
2.
Application.Current.Dispatcher.Invoke(new Action(() => {
//Add the feature code above here
}));
3.
Task task = new Task(()=> {
//Add the feature code above here
});
task.Start();
task.Wait();
那么,谁能告诉我如何使它工作?