首页 > 解决方案 > 在 WPF 中,如何更新用户控件中的主 UI?

问题描述

我有一个问题。我想在一个用户控件中更新主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();

那么,谁能告诉我如何使它工作?

标签: c#.netwpfuser-interfacedispatcher

解决方案


这不是它的完成方式。设置类的属性也不称为绑定。这是一个简单的任务。

ABinding连接两个或多个 ( MultiBinding) 属性(目标和源)并在两者之一发生更改时自动更新它们。
要允许绑定检测属性更改,您必须将参与的属性实现为DependencyProperty(绑定目标的强制性 - 最好在控件上)或让它们INotifyPropertyChanged.PropertyChanged在属性更改时引发事件。

  1. 创建数据和绑定源

    主窗口.xaml

    partial class MainWindow : Window
    {
      public static readonly DependencyProperty InfoProperty = DependencyProperty.Register(
        "Info",
        typeof(string),
        typeof(MainWindow),
        new PropertyMetadata(default(string)));
    
      public string Info
      {
        get => (string) GetValue(MainWindow.InfoProperty);
        set => SetValue(MainWindow.InfoProperty, value);
      }
    
      // Update the TextBlock via data binding
      public void ShowInfo(string info)
      {
        this.Info = info;
      }
    }
    
  2. 创建 UI 并设置数据绑定

    主窗口.xaml

    <Window>
      <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, 
                                Path=Info}" />
    </Window>
    

请参阅 Microsoft 文档:

WPF 中的数据绑定概述

如何:实现依赖属性


推荐阅读