WPF绑定到自定义控件中的自定义属性
我有一个自定义文本框,定义如下:WPF绑定到自定义控件中的自定义属性,wpf,binding,Wpf,Binding,我有一个自定义文本框,定义如下: public class CustomTextBox : TextBox { public static DependencyProperty CustomTextProperty = DependencyProperty.Register("CustomText", typeof(string), typeof(CustomTextBox)); static CustomTextBox(
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}" />
您可能还必须为更新
Text
属性的CustomText
属性定义PropertyChangedCallback(即您现在实现的另一个方向)。否则,文本框将不会显示最初包含在ViewModel属性中的任何内容,当然,当ViewModel属性更改时,文本框也不会更新。PropertyChanged回调有什么作用?对我来说,看起来你刚刚设置了一个新的值,这就是调用这个回调的原因,幸运的是,它再次被wpf捕获,否则你将有一个无休止的循环。谢谢!!成功了。但是,当我没有在文本框中输入任何内容并尝试刷新页面时(我认为它会刷新UC,但我不是很确定),我会得到这样一个异常:Key不能为null。参数名称:keyName听起来与此属性或绑定无关。“刷新页面”的确切含义是什么?有一个按钮可以对所有字段执行验证(这是使用IDataErrorInfo完成的,并重新分配每个属性的值)。当我点击这个按钮时,它会毫无问题地通过验证,但一旦验证完成,应用程序就会抛出上面提到的异常。我尝试删除绑定(并使用TextBox的Text属性),效果很好。当我绑定CustomText/Text属性时,会出现异常,这就是为什么我认为是绑定导致了问题。仍然很难说名为“key”的参数到底是什么,它是null。您的ViewModelProperty
是否不能为空?可能您需要指定string.Empty
作为CustomText
属性的默认值。ViewModelProperty可以为null-这是一个无效值,但应该在有效的验证过程中处理,即为该场景正确分配错误消息。为了以防万一,我也为CustomText指定了一个默认值,但它仍然不起作用。异常的堆栈跟踪对我也没有多大帮助,因为它没有指向代码中的任何内容
public static readonly DependencyProperty CustomTextProperty =
DependencyProperty.Register(
"CustomText", typeof(string), typeof(CustomTextBox),
new FrameworkPropertyMetadata(
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));