c# - 在 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();
那么,谁能告诉我如何使它工作?
解决方案
这不是它的完成方式。设置类的属性也不称为绑定。这是一个简单的任务。
ABinding
连接两个或多个 ( MultiBinding
) 属性(目标和源)并在两者之一发生更改时自动更新它们。
要允许绑定检测属性更改,您必须将参与的属性实现为DependencyProperty
(绑定目标的强制性 - 最好在控件上)或让它们INotifyPropertyChanged.PropertyChanged
在属性更改时引发事件。
创建数据和绑定源
主窗口.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; } }
创建 UI 并设置数据绑定
主窗口.xaml
<Window> <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=Info}" /> </Window>
请参阅 Microsoft 文档:
推荐阅读
- sql - SQL 将行转换为列并填充值
- java - setOnClickListener Android Studio(制作计数器)
- javascript - 通过代理的 Google Places API 超时
- cypress - 比较赛普拉斯中的动态文本
- reactjs - 在反应图中具有相同x轴的多个y轴值
- javascript - 如何根据字段是否存在对 MongoDB 集合进行排序
- python - 子类 __init__ 中 PyMissingConstructor 的 PyCharm 警告,但超类没有 __init__
- angular - 网址的角度有多深?
- sql-server - 从列中获取最近的日期
- python - 在 Django 中,如何在装饰函数中的请求对象中设置值并从装饰函数中的请求对象访问它