繁体   English   中英

在WPF用户控件中访问控件属性时出错

[英]error on accessing a property of a control in a wpf user control

我创建了一个带有文本框和组合框的wpf用户控件。 为了访问文本框的text属性,我使用了以下代码

public static readonly DependencyProperty TextBoxTextP = DependencyProperty.Register(
        "TextBoxText", typeof(string), typeof(TextBoxUnitConvertor));

public string TextBoxText
{
    get { return txtValue.Text; }
    set { txtValue.Text = value; }
}

在另一个项目中,我使用了控件并将文本绑定如下:

<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且绑定不起作用。 谁能帮我?

您的依赖项属性声明错误。 它必须看起来如下所示,其中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中,您将像这样绑定到属性:

<TextBox Text="{Binding TextBoxText,
    RelativeSource={RelativeSource AncestorType=UserControl}}" />

如果每当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到的值txtValue.Text

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM