WPF Binding to a custom property in a custom control

前端 未结 1 1216
余生分开走
余生分开走 2020-12-19 07:39

I have a custom text box defined as follows:

public class CustomTextBox : TextBox
{
    public static DependencyProperty CustomTextProperty = 
             D         


        
相关标签:
1条回答
  • 2020-12-19 08:26

    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.

    0 讨论(0)
提交回复
热议问题