Data binding 将代码中的简单数据绑定到DependencyProperty

Data binding 将代码中的简单数据绑定到DependencyProperty,data-binding,silverlight-4.0,dependencyobject,Data Binding,Silverlight 4.0,Dependencyobject,我很抱歉,因为这太简单了,我知道问题已经回答了,但在30页左右的篇幅里,我还没有找到我试图解决的问题 我还没有很好地使用SL,尝试编写一个简单版本的文本框,该文本框绑定到屏幕中的属性,并在文本更改时更新它,反之亦然(属性更改传播到文本)。由于一些原因,我需要使用DependencyProperties并在codebehind中执行此操作,而不是使用INotifyPropertyChanged和XAML 我最近的尝试如下所示: public partial class MainPage :

我很抱歉,因为这太简单了,我知道问题已经回答了,但在30页左右的篇幅里,我还没有找到我试图解决的问题

我还没有很好地使用SL,尝试编写一个简单版本的文本框,该文本框绑定到屏幕中的属性,并在文本更改时更新它,反之亦然(属性更改传播到文本)。由于一些原因,我需要使用DependencyProperties并在codebehind中执行此操作,而不是使用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;
    }
}
有人看到我错过了什么(显而易见的痛苦吗?)

谢谢


John

以下内容应足以设置所需的绑定:

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

代码的问题是,您将
Source
和绑定
Path
都设置为
TargetText
属性,结果是框架试图绑定到
TargetText.TargetText
,这显然是错误的。

知道这是一件简单的事情,但却盲目地试图看到它。谢谢你,帕夫洛!这不适合我。I get:无法将源类型“string”转换为目标类型“System.Windows.PropertyPath”