要将字符串绑定到WPF RichTextBox,可以使用Text属性和绑定机制。以下是一个示例:
XAML代码:
C#代码:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string myText;
public string MyText
{
get { return myText; }
set
{
myText = value;
OnPropertyChanged();
}
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
// 初始化绑定的字符串
MyText = "Hello, world!";
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
在上述示例中,我们在MainWindow的构造函数中初始化了绑定的字符串。通过将RichTextBox的Text属性绑定到MyText属性,并实现INotifyPropertyChanged接口,当MyText属性的值更改时,RichTextBox会自动更新其内容。
下一篇:绑定子元素并进行额外数据获取