WPF Binding to a custom property in a custom control
binding, wpf
Solution
I guess the binding needs to be two-way.
<local:CustomTextBox
CustomText="{Binding ViewModelProperty, Mode=TwoWay}" />
You wouldn't need to specify the `Mode` if you made the `CustomText` property bind two-way by default:
public static readonly DependencyProperty CustomTextProperty =
DependencyProperty.Register(
"CustomText", typeof(string), typeof(CustomTextBox),
new FrameworkPropertyMetadata(
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
You may also have to define a PropertyChangedCallback for the `CustomText` property that updates the `Text` property (i.e. the other direction of what you have implemented now). Otherwise the TextBox won't display anything that is initially contained in the ViewModel property and of course woudln't be updated when the ViewModel property changes.
Problem
I have a custom text box defined as follows: ``` public class CustomTextBox : TextBox { public static DependencyProperty CustomTextProperty = DependencyProperty.Register("CustomText", typeof(string), typeof(CustomTextBox)); static CustomTextBox() { TextProperty.OverrideMetadata(typeof(SMSTextBox), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(CustomTextBox_OnTextPropertyChanged)); } public string CustomText { get { return (string)GetValue(CustomTextProperty); } set { SetValue(CustomTextProperty, value); } } private static void CustomTextBox_OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CustomTextBox customTextBox = d as CustomTextBox; customTextBox.SetValue(CustomTextProperty, e.NewValue); } } ``` I'm binding the Custom Text property in the XAML - ``` <local:CustomTextBox CustomText="{Binding ViewModelProperty}" /> ``` The problem I'm facing is that when I enter anything in the CustomTextBox, the changes are not reflected in the ViewModelProperty i.e. the ViewModelProperty is not getting updated. The CustomTextProperty is getting updated but I suppose I need to do something extra to make the binding work as well. What am I not doing? I would appreciate any help regarding this. Thank you