My apologies as this is simplistic enough I know the question's been answered but in 30 or so pages, I've yet to find the boiled down problem I'm trying to solve.
I'm not yet well practiced in SL and trying a simple version of attempting to write a TextBox that binds to a property within the screen and updates it when Text is altered and vice versa (property change propagates to the Text). Due to a few reasons, I need to do this with DependencyProperties and in the codebehind rather than INotifyPropertyChanged and in XAML.
My latest attempts look something like this:
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;开发者_C百科
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;
}
}
Anyone see what (painfully obvious thing?) I'm missing?
Thanks,
John
The following should be enough to set the binding you want:
textBox1.SetBinding(TextBox.TextProperty, new Binding() { Path = "TargetText", Source = this });
The problem with your code is that you set both Source
and binding Path
to the TargetText
property and as a result you get the framework trying to bind to TargetText.TargetText
, which is obviously wrong.
精彩评论