Csharp/C#教程:访问wpf用户控件中控件的属性时出错分享


访问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的值

上述就是C#学习教程:访问wpf用户控件中控件的属性时出错分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1011846.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐