我使用本教程构建了一个自定义控件。现在,我想在用户控件中添加一个简单的消息(文本块)来给用户一些指导。我想我可以添加一个公共属性,例如教程中的 FileName,但是如何将文本块的 Text 属性连接到后面代码中的属性?然后确保在属性更改时更新文本块消息。
我喜欢能够通过属性在代码中设置消息的想法,因为我可能会在页面上有多个这种自定义控件类型的控件。我只是有点难为它接线。
谢谢!
我使用本教程构建了一个自定义控件。现在,我想在用户控件中添加一个简单的消息(文本块)来给用户一些指导。我想我可以添加一个公共属性,例如教程中的 FileName,但是如何将文本块的 Text 属性连接到后面代码中的属性?然后确保在属性更改时更新文本块消息。
我喜欢能够通过属性在代码中设置消息的想法,因为我可能会在页面上有多个这种自定义控件类型的控件。我只是有点难为它接线。
谢谢!
这将是您的代码,它实现了 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)。