I used this http://www.c-sharpcorner.com/uploadfile/mahesh/user-control-in-wpf/构建自定义控件的教程。现在,我想向用户控件添加一条简单的消息(文本块)来为用户提供一些指导。我想我可以添加一个公共属性,例如教程中的 FileName,但是如何将文本块的 Text 属性连接到后面代码中的属性?然后确保文本块消息在属性更改时更新。
我喜欢能够通过属性在代码中设置消息的想法,因为我可能会在页面上拥有此自定义控件类型的多个控件。我只是对接线有点困惑。
Thanks!
这将是您的隐藏代码,它实现了 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}" />
EDIT:
Added 数据上下文=这个;我通常不绑定到后面的代码(我使用 MVVM)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)