簡體   English   中英

WPF:創建附加的可綁定屬性

[英]WPF: Creating attached bindable property

我正在嘗試添加一個屬性,該屬性可以附加到任何控件並為其綁定一個值。

public class ValidationBorder : DependencyObject
    {
        public static readonly DependencyProperty HasErrorProperty =
            DependencyProperty.Register(
                "HasError",
                typeof(bool?),
                typeof(UIElement),
                new PropertyMetadata(default(Boolean))
            );

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

        public static void SetHasError(UIElement element, Boolean value)
        {
            element.SetValue(HasErrorProperty, value);
        }
        public static Boolean GetHasError(UIElement element)
        {
            return (Boolean)element.GetValue(HasErrorProperty);
        }
    }

我的用法:

<TextBox Text="{Binding SelectedFrequencyManual, UpdateSourceTrigger=PropertyChanged}" TextAlignment="Center"
                         attached:ValidationBorder.HasError="{Binding Path=DataOutOfRange}">
                </TextBox>

當我啟動項目時,它顯示錯誤(已翻譯):

不能在TextBox setHasError屬性中指定Binding。 只能在DependencyObject的DependencyProperty中指定綁定

這有什么問題呢?

我已經嘗試了所有可以在網上找到的內容:

  • 在綁定中添加括號
  • 添加RelativeSource
  • 更改DependencyProperty.RegisterDependencyProperty.RegisterAttached
  • typeof(UIElement)不同類型,包括typeof(TextBox)

試試這個實現:

public class ValidationBorder
{
    public static readonly DependencyProperty HasErrorProperty =
        DependencyProperty.RegisterAttached(
            "HasError",
            typeof(bool?),
            typeof(ValidationBorder),
            new PropertyMetadata(default(bool?))
        );

    public static void SetHasError(UIElement element, bool? value)
    {
        element.SetValue(HasErrorProperty, value);
    }
    public static bool? GetHasError(UIElement element)
    {
        return (bool?)element.GetValue(HasErrorProperty);
    }
}

您應該調用RegisterAttached並將所有者類型設置為ValidationBorder 還刪除HasError屬性。 請參考文檔以獲取更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM