我使用了此教程来构建一个自定义控件。现在,我想向用户控件添加一条简单的消息(文本块),为用户提供一些指导。我想我可以添加一个公共属性,例如本教程中的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设置为属性值?
发布评论