如何为以下XAML代码创建C#代码?

时间:2013-09-19 06:27:16

标签: c# xaml windows-phone-7 windows-phone-8 windows-phone

我在XAML中完成了以下代码。但是,我不想在XAML中创建文本绑定。无论如何都要以编程方式在C#中创建相同的方法吗?

XAML代码:

<TextBox Name="contentBox"  Text="{Binding Content, Mode=TwoWay}" AcceptsReturn="True" />

3 个答案:

答案 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插入到您的可视树中。