我在 XAML 中完成了以下代码。但是,我不想在 XAML 中创建文本绑定。反正有没有以编程方式在 C# 中创建相同的方法?
XAML 代码:
<TextBox Name="contentBox" Text="{Binding Content, Mode=TwoWay}" AcceptsReturn="True" />
我在 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);
您仍然需要INotifyPropertyChanged
为您DataContext
的 .
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);