WPF绑定到一个自定义属性自定义控制
我定义了一个自定义文本框,如下所示:WPF绑定到一个自定义属性自定义控制
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正在更新,但我想我需要做一些额外的事情来完成绑定工作。
我没有做什么?我将不胜感激这方面的帮助。
谢谢
我想绑定需要是双向的。
<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));
您可能还需要定义一个PropertyChangedCallback为CustomText
属性,更新Text
属性(即您现在实施的其他方向)。否则,TextBox将不显示最初包含在ViewModel属性中的任何内容,当ViewModel属性更改时当然不会更新。
谢谢!这工作。但是,当我没有在文本框中输入任何内容并尝试刷新页面(我认为它刷新了UC,但我不确定)时,我得到如下异常: 键不能为空。 参数名称:密钥 –
听起来不像是与此属性或绑定有关的事情。什么意思是“刷新页面”? – Clemens
有一个按钮在所有字段上执行验证(这是使用IDataErrorInfo完成的,并为每个属性重新赋值)。当我点击这个按钮时,它会在没有任何问题的情况下通过验证,但是一旦完成,应用程序就会抛出上述异常。我尝试删除绑定(并使用TextBox的Text属性),它工作得很好。当我绑定CustomText/Text属性时,我得到异常,这就是为什么我认为它是导致问题的绑定。 –
你想用PropertyChanged回调来完成什么?对我来说,它看起来像你只是设置一个新的价值,这就是为什么这个回调被称为,它再次幸运地被wpf捕获,否则你会有一个无限循环。 – dowhilefor