访问wpf用户控件中控件的属性时出错
我创建了一个带有文本框和combobox的wpf用户控件。 为了访问文本框的文本属性,我使用了以下代码
public static readonly DependencyProperty TextBoxTextP = DependencyProperty.Register( "TextBoxText", typeof(string), typeof(TextBoxUnitConvertor)); public string TextBoxText { get { return txtValue.Text; } set { txtValue.Text = value; } }
在另一个项目中,我使用了控件并绑定了如下文本:
我确定用于绑定的类正常工作,因为当我用它来直接在我的项目中使用文本框时它可以正常工作但是当我将它绑定到usercontrol中textbox的text属性时它会带来null和绑定不起作用。 谁能帮我?
您的依赖项属性声明是错误的。 它必须如下所示,其中CLR属性包装器的getter和setter调用GetValue和SetValue方法:
public static readonly DependencyProperty TextBoxTextProperty = DependencyProperty.Register( "TextBoxText", typeof(string), typeof(TextBoxUnitConvertor)); public string TextBoxText { get { return (string)GetValue(TextBoxTextProperty); } set { SetValue(TextBoxTextProperty, value); } }
在UserControl的XAML中,您将绑定到属性,如下所示:
如果您需要在TextBoxText
属性更改时收到通知,您可以使用传递给Register方法的PropertyMetadata注册PropertyChangedCallback:
public static readonly DependencyProperty TextBoxTextProperty = DependencyProperty.Register( "TextBoxText", typeof(string), typeof(TextBoxUnitConvertor), new PropertyMetadata(TextBoxTextPropertyChanged)); private static void TextBoxTextPropertyChanged( DependencyObject o, DependencyPropertyChangedEventArgs e) { TextBoxUnitConvertor t = (TextBoxUnitConvertor)o; t.CurrentValue = ... }
您没有创建依赖项属性。 使用此代码:
public string TextBoxText { get { return (string)GetValue(TextBoxTextProperty); } set { SetValue(TextBoxTextProperty, value); } } public static readonly DependencyProperty TextBoxTextProperty = DependencyProperty.Register("TextBoxText", typeof(string), typeof(TextBoxUnitConvertor), new PropertyMetadata(""));
然后在您的自定义控件中将TextBoxText
绑定到TextBoxText
的值