WPF绑定到自定义控件中的自定义属性

时间:2013-01-31 14:37:41

标签: wpf binding

我有一个自定义文本框,定义如下:

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);
    }
}

我正在绑定XAML中的自定义文本属性 -

<local:CustomTextBox CustomText="{Binding ViewModelProperty}" />

我面临的问题是,当我在CustomTextBox中输入任何内容时,更改不会反映在ViewModelProperty中,即ViewModelProperty没有得到更新。 CustomTextProperty正在更新,但我想我需要做一些额外的工作来使绑定工作。

我不做什么?对此我有任何帮助,我将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:6)

我想绑定需要双向。

<local:CustomTextBox
    CustomText="{Binding ViewModelProperty, Mode=TwoWay}" />

如果默认情况下将Mode属性绑定为双向,则无需指定CustomText

public static readonly DependencyProperty CustomTextProperty =
    DependencyProperty.Register(
        "CustomText", typeof(string), typeof(CustomTextBox),
        new FrameworkPropertyMetadata(
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

您可能还必须为更新CustomText属性的Text属性定义PropertyChangedCallback(即您现在实现的其他方向)。否则,TextBox将不会显示最初包含在ViewModel属性中的任何内容,当然,当ViewModel属性发生更改时,不会更新。