2

我很抱歉,因为这太简单了,我知道问题已经得到解答,但是在 30 左右页中,我还没有找到我想要解决的归结问题。

我还没有在 SL 中得到很好的实践,并尝试了一个简单的版本,尝试编写一个 TextBox,它绑定到屏幕内的一个属性,并在 Text 被更改时更新它,反之亦然(属性更改传播到 Text)。由于一些原因,我需要使用 DependencyProperties 和代码隐藏而不是 INotifyPropertyChanged 和 XAML 来执行此操作。

我最近的尝试是这样的:

    public partial class MainPage : UserControl
{
    static MainPage()
    {
        TargetTextProperty = DependencyProperty.Register("TargetText", typeof(string), typeof(MainPage), new PropertyMetadata(new PropertyChangedCallback(TextChanged)));
    }

    public readonly static DependencyProperty TargetTextProperty;

    public string TargetText
    {
        get { return (string)GetValue(TargetTextProperty); }
        set { SetValue(TargetTextProperty, value); }
    }

    public MainPage()
    {
        InitializeComponent();

        TargetText = "testing";
        textBox1.DataContext = TargetText;
        Binding ResetBinding = new Binding("TargetText");
        ResetBinding.Mode = BindingMode.TwoWay;
        ResetBinding.Source = TargetText;

        textBox1.SetBinding(TextBox.TextProperty, ResetBinding);
    }

    private static void TextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MainPage pg = (MainPage)sender;
        pg.textBox1.Text = e.NewValue as string;
    }
}

任何人都看到我错过了什么(非常明显的事情?)?

谢谢,

约翰

4

1 回答 1

4

以下应该足以设置您想要的绑定:

textBox1.SetBinding(TextBox.TextProperty, new Binding() { Path = "TargetText", Source = this });

您的代码的问题是您设置Source并绑定PathTargetText属性,结果您让框架尝试绑定到TargetText.TargetText,这显然是错误的。

于 2011-06-02T13:14:36.660 回答