我在XAML中完成了以下代码。但是,我不想在XAML中创建文本绑定。无论如何都要以编程方式在C#中创建相同的方法吗?
XAML代码:
<TextBox Name="contentBox" Text="{Binding Content, Mode=TwoWay}" AcceptsReturn="True" />
答案 0 :(得分:1)
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);
答案 1 :(得分:0)
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);
答案 2 :(得分:0)
看起来像这样:
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
类,并手动将代码创建的TextBox插入到您的可视树中。