我有一个自定义文本框定义如下:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在绑定XAML中的自定义文本属性 -
<local:CustomTextBox CustomText="{Binding ViewModelProperty}" />
Run Code Online (Sandbox Code Playgroud)
我面临的问题是,当我在CustomTextBox中输入任何内容时,更改不会反映在ViewModelProperty中,即ViewModelProperty没有得到更新.CustomTextProperty正在更新,但我想我需要做一些额外的事情来使绑定工作.
我不做什么?我将不胜感激任何帮助.
谢谢
我想绑定需要双向.
<local:CustomTextBox
CustomText="{Binding ViewModelProperty, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)
你不会需要指定Mode,如果你所做的CustomText默认属性绑定双向的:
public static readonly DependencyProperty CustomTextProperty =
DependencyProperty.Register(
"CustomText", typeof(string), typeof(CustomTextBox),
new FrameworkPropertyMetadata(
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
Run Code Online (Sandbox Code Playgroud)
您可能还必须为CustomText更新Text属性的属性(即您现在实现的其他方向)定义PropertyChangedCallback .否则,TextBox将不会显示最初包含在ViewModel属性中的任何内容,当然,当ViewModel属性更改时,不会更新.