在WPF中,如何在用户控件中更新主UI?

问题描述 投票:0回答:1

我有一个问题。我想更新用户控件中的主UI。我尝试了很多次,但是没有成功。测试分为以下两类:

第1类:

我首先没有成功地直接分配了主窗口控件(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();

所以,有人可以告诉我如何使它正常工作吗?

c# .net wpf user-interface dispatcher
1个回答
0
投票

我假设您没有使用带有绑定的MVVM结构。

为您自己设置一个函数,例如'SomeFunctionToChangeValue',该函数会更改您想要的控制值,例如文本字段。

然后这样称呼它:

string textValue = "new text to display";
SomeFunctionToChangeValue.?Invoke( textValue);
© www.soinside.com 2019 - 2024. All rights reserved.