在wpf用户控件中访问控件的属性时出错 [英] error on accessing a property of a control in a wpf user control
问题描述
我用文本框和组合框创建了一个wpf用户控件. 为了访问文本框的text属性,我使用了以下代码
i have created a wpf user control with a text box and a combo box. for accessing the text property of the text box i have used the below code
public static readonly DependencyProperty TextBoxTextP = DependencyProperty.Register(
"TextBoxText", typeof(string), typeof(TextBoxUnitConvertor));
public string TextBoxText
{
get { return txtValue.Text; }
set { txtValue.Text = value; }
}
在另一个项目中,我使用了控件并将文本绑定如下:
in another project i have used the control and bind the text as below:
<textboxunitconvertor:TextBoxUnitConvertor Name="wDValueControl" TextBoxText="{Binding _FlClass.SWa_SC.Value , RelativeSource={RelativeSource AncestorType=Window}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="161" Height="28" HorizontalAlignment="Left" VerticalAlignment="Top"/>
我确定用于绑定的类可以正常工作,因为当我使用它直接在项目中与文本框bing时,它可以正常工作,但是当我将其绑定到usercontrol中的textbox的text属性时,它将带来null,并且绑定不起作用. 有人可以帮我吗?
i am certain that the class that is used for binding is properly working because when i used it to bing with a text box directly in my project it works properly but when i bind it to the text property of textbox in usercontrol it brings null and the binding does not work. can any one help me?
推荐答案
您的依赖项属性声明错误.它必须看起来如下所示,其中CLR属性包装器的getter和setter调用GetValue和SetValue方法:
Your dependency property declaration is wrong. It has to look like shown below, where the getter and setter of the CLR property wrapper call the GetValue and SetValue methods:
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中,您将这样绑定到属性:
In the XAML of your UserControl, you would bind to the property like this:
<TextBox Text="{Binding TextBoxText,
RelativeSource={RelativeSource AncestorType=UserControl}}" />
如果每当TextBoxText
属性发生更改时需要通知,则可以使用传递给Register方法的PropertyMetadata来注册PropertyChangedCallback:
If you need to get notified whenever the TextBoxText
property changes, you could register a PropertyChangedCallback with PropertyMetadata passed to the Register method:
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 = ...
}
这篇关于在wpf用户控件中访问控件的属性时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!