Skip to main content
Home Forums Silverlight Programming Silverlight Controls and Silverlight Toolkit TextBox.Text won't bind trough a dependency property
2 replies. Latest Post by mrjvdveen on July 2, 2009.
(0)
mrjvdveen
Participant
1749 points
331 Posts
07-01-2009 8:53 AM |
Here is what I'm trying to do. I want to have a control that combines a TextBlock to display a label and a TextBox to display/edit a value. As this combines two basic controls, I figured I would go with a UserControl. The Xaml for it is very easy:
<StackPanel x:Name="stackPanel"> <TextBlock x:Name="labelTextBlock" Style="{StaticResource LabeledTextBoxLabel}"/> <TextBox x:Name="textBox" Style="{StaticResource LabeledTextBoxTextBox}"/> </StackPanel>
All is still well.
I've added some dependency properties to my new LabeledTextBox UserControl, to allow setting some properties on the underlying controls. One of these properties is the Text property:
public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); UpdateText(value); } } // Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc... public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(LabeledTextBox), new PropertyMetadata(string.Empty));
The UpdateText(value) line only passes the value to the textBox.Text property. Now in my application I want to databind to the Text property of my UserControl, which in turn should pass the binding to the textBox inside. It doesn't databind. It doesn't show any initial values.
Help?
Ag.
Member
101 points
19 Posts
07-01-2009 10:55 AM |
You should call UpdateText in the property changed callback not in the setter
public string Text { get { return (string) GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof (string), typeof (LabeledTextBox), new PropertyMetadata(string.Empty, OnTextChanged)); private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var labeledTextBox = d as LabeledTextBox; if (labeledTextBox == null) return; labeledTextBox.UpdateText(e.NewValue as string); }
Best Regards
Valery Sarkisov
07-02-2009 3:04 AM |
That does actually work! Thanks.
However I don't realy understand why my solution does work for a usercontrol wrapping a combobox. I used exactly the same method for passing on bindings to the selecteditem property and it works fine. Any insights?