如何将TextBlock设置为属性值?

编程入门 行业动态 更新时间:2024-10-19 23:26:39
本文介绍了如何将TextBlock设置为属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用了此教程来构建一个自定义控件。现在,我想向用户控件添加一条简单的消息(文本块),为用户提供一些指导。我想我可以添加一个公共属性,例如本教程中的FileName,但是如何将文本块的Text属性连接到后面代码中的属性上呢?然后确保如果属性更改,文本消息也将更新。

I used this tutorial to build a custom control. Now, I'd like to add a simple message (a textblock) to the user control to give the user some guidance. I think I can add a public property, like FileName in the tutorial, but how do I wire up the textblock's Text property to the property in the code behind? And then make sure the textblock message updates if the property changes.

我喜欢能够通过属性在代码中设置消息的想法,因为我很可能在页面上具有此自定义控件类型的多个控件。

I like the idea of being able to set the message in code, via a property, because I will likely have multiple controls of this custom control type on a page. I'm just a bit stumped on wiring it up.

谢谢!

推荐答案

这将是后面的代码,该代码实现INotifyPropertyChanged:

This would be your code behind, which implements INotifyPropertyChanged:

/// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _fileName; /// <summary> /// Get/Set the FileName property. Raises property changed event. /// </summary> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; RaisePropertyChanged("FileName"); } } } public MainWindow() { DataContext = this; FileName = "Testing.txt"; } private void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }

这将是您的XAML绑定到该属性:

This would be your XAML that binds to the property:

<TextBlock Text="{Binding FileName}" />

编辑:

已添加 DataContext = this; 我通常不绑定到背后的代码(我使用MVVM)。

Added DataContext = this; i don't normally bind to the code behind (I use MVVM).

更多推荐

如何将TextBlock设置为属性值?

本文发布于:2023-11-13 02:04:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   如何将   属性   TextBlock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!