0

我有两个文本框txt1txt2一个字符串依赖属性sprop

public static readonly DependencyProperty spropProperty = DependencyProperty.Register("sprop", typeof (string), typeof (MainWindow), new UIPropertyMetadata(string.Empty));

public string sprop
{
    get { return (string) this.GetValue(spropProperty); }
    set { this.SetValue(spropProperty, value); }
}

txt1现在,如果我以这种方式在 XAML 中设置数据绑定:

Text="{Binding sprop, ElementName=window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}

txt1sprop每当文本框文本发生更改时,都会立即更新。

txt2但是,如果我以这种方式在 C# 中设置数据绑定:

DataContext = this;
txt2.SetBinding(TextBox.TextProperty, "sprop");

然后仅在失去焦点时txt2更新。sprop

如何使用 C# 代码在文本更改sprop后立即更新txt2


我试过的:

DataContext = this;
var myBinding = new Binding("sprop");
myBinding.Source = this;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
txt2.SetBinding(TextBlock.TextProperty, myBinding);
4

2 回答 2

2

您还需要在 txt2 中设置 UpdateSourceTrigger 以便在属性更改后进行更新,您也可以在代码中设置:

Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myBinding.Mode = TwoWay;
myBinding.UpdateSourceTrigger = PropertyChanged;
myText.SetBinding(TextBlock.TextProperty, myBinding);
于 2012-09-17T20:05:48.297 回答
1

您是否将 txt2 设置为 Mode=TwoWay?

于 2012-09-17T21:16:45.690 回答