【问题标题】:DependencyProperty for TextBox gives compile time error (UWP)TextBox 的 DependencyProperty 给出编译时错误 (UWP)
【发布时间】:2020-08-16 16:00:18
【问题描述】:

我有一个带有 DependencyProperty 的文本框,代码如下所示

<UserControl
x:Class="Projectname.Controls.Editors.EditTextControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:ui="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
mc:Ignorable="d">

<Grid>
    <TextBox  PlaceholderText="I'am Active"   HasError="{Binding IsInvalid, UpdateSourceTrigger=PropertyChanged}"  Height="80" Width="300"  x:Name="txtActive"  Text="{Binding TextValue, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" ></TextBox>
</Grid>

  public sealed partial class EditTextControl : UserControl
{
    TestViewModel TV = new TestViewModel();
    public EditTextControl()
    {
        this.InitializeComponent();
        this.DataContext = TV;
    }

    public bool HasError
    {
        get { return (bool)GetValue(HasErrorProperty); }
        set { SetValue(HasErrorProperty, value); }
    }

    /// <summary>
    /// This is a dependency property that will indicate if there's an error. 
    /// This DP can be bound to a property of the VM.
    /// </summary>
    public static readonly DependencyProperty HasErrorProperty =
        DependencyProperty.Register("HasError", typeof(bool), typeof(EditTextControl), new PropertyMetadata(false, HasErrorUpdated));


    // This method will update the Validation visual state which will be defined later in the Style
    private static void HasErrorUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        EditTextControl textBox = d as EditTextControl;

        if (textBox != null)
        {
            if (textBox.HasError)
                VisualStateManager.GoToState(textBox, "InvalidState", false);
            else
                VisualStateManager.GoToState(textBox, "ValidState", false);
        }
    }
}

对我来说一切都很好,但在编译时本身,它会给出这些错误。

The property 'HasError' was not found in type 'TextBox'.
The member "HasError" is not recognized or is not accessible.

谁能指出我在这里做错了什么?

【问题讨论】:

    标签: c# xaml uwp dependency-properties


    【解决方案1】:

    HasErrorEditTextControl 用户控件上的属性,而不是 TextBox 上的属性。 如果要向 TextBox 类添加自定义属性,请使用 Attached Property 而不是 Dependency 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2023-03-26
      • 1970-01-01
      • 2013-07-16
      • 2015-12-31
      • 1970-01-01
      相关资源
      最近更新 更多