WPF后台创建控件和绑定
WPF后台创建控件和绑定
一、创建一个类:
public class MyData : INotifyPropertyChanged
{
private string text;
public string Text
{
get { return text; }
set
{
text = value;
OnPropertyChanged(nameof(Text));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
创建控件并绑定数据:
public partial class MainWindow : Window
{
private MyData myData = new MyData();
public MainWindow()
{
InitializeComponent();
// 创建TextBox控件
TextBox textBox = new TextBox();
// 绑定数据源
textBox.SetBinding(TextBox.TextProperty, new Binding("Text") { Source = myData });
// 添加到布局容器中
this.Content = textBox;
// 或者你也可以将其添加到已有的布局面板中
// myGrid.Children.Add(textBox);
// 测试数据绑定
myData.Text = "Hello, WPF!";
}
}