如何为以下 XAML 代码创建 C# 代码
本文关键字:代码 创建 XAML | 更新日期: 2023-09-27 18:32:07
我在 XAML 中完成了以下代码。但是,我不想在 XAML 中创建文本绑定。 无论如何可以在 C# 中以编程方式创建相同的方法吗?
XAML 代码:
<TextBox Name="contentBox" Text="{Binding Content, Mode=TwoWay}" AcceptsReturn="True" />
TextBox tb = new TextBox();
tb.Name = "contentBox";
tb.AcceptsReturn = true;
Binding b = new Binding("Content");
b.Mode = BindingMode.TwoWay;
b.Source = this; // set you DataContext here
tb.SetBinding(TextBlock.TextProperty, b);
它看起来像这样:
var tb = new TextBox();
tb.SetValue(NameProperty, "contentBox");
tb.AcceptsReturn = true;
var b = new Binding("Content");
b.Mode = BindingMode.TwoWay;
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(tb, TextBox.TextProperty, b);
您仍然需要为DataContext
实现一个INotifyPropertyChanged
类,并手动将代码创建的 TextBox 插入到可视化树中的某个位置。
Binding binding = new Binding();
binding.Mode = BindingMode.TwoWay;
binding.Path = new PropertyPath("Content"); //Name of the property in Datacontext
BindingOperations.SetBinding(contentBox,TextBox.TextProperty , binding);