【问题标题】:How do I set a TextBlock to a property value?如何将 TextBlock 设置为属性值?
【发布时间】:2013-07-20 03:52:50
【问题描述】:
我使用this 教程构建了一个自定义控件。现在,我想在用户控件中添加一个简单的消息(文本块)来给用户一些指导。我想我可以添加一个公共属性,例如教程中的 FileName,但是如何将文本块的 Text 属性连接到后面代码中的属性?然后确保在属性更改时更新文本块消息。
我喜欢能够通过属性在代码中设置消息的想法,因为我可能会在页面上有多个这种自定义控件类型的控件。我只是有点难为它接线。
谢谢!
【问题讨论】:
标签:
wpf
.net-4.0
wpf-controls
【解决方案1】:
这将是您的代码,它实现了 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:
<TextBlock Text="{Binding FileName}" />
编辑:
添加 DataContext = this; 我通常不会绑定到后面的代码(我使用 MVVM)。