簡體   English   中英

如何在UserControl中使用綁定的XAML屬性?

[英]How to use bound XAML property in UserControl?

我有自己的UserControl

 <local:MyUserControl MyProperty="{Binding myString}"/>                                      

然后將myString綁定到它。 現在,我想在UserControl使用它。 我在UserControl定義了DependencyProperty

    public string MyProperty
    {
        get { return (string)GetValue(MyPropertyProperty); }
        set
        {
            Debug.WriteLine(value);//writes nothing, null
            SetValue(MyPropertyProperty, value);
        }
    }
    public static readonly DependencyProperty MyPropertyProperty =
      DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata(null));

我究竟做錯了什么? 我想用這個字符串做一些事情。 但它始終為空。

Debug.WriteLine(value); 不寫任何東西,不是因為值是null 不能保證運行依賴項屬性的getter和setter,而使用{Binding} ,不會調用屬性的setter。 您可以在設置器中添加一個斷點進行測試。

請注意“ 自定義依賴項屬性”中的以下注意事項:

在除特殊情況以外的所有情況下,包裝器實現都應僅執行GetValue和SetValue操作。 否則,通過XAML設置屬性與通過代碼設置屬性時,您將獲得不同的行為。 為了提高效率,XAML解析器在設置依賴項屬性時會繞過包裝器。 只要有可能,它將使用依賴項屬性的注冊表。

您可以在對DependencyProperty.Register的原始調用中添加一個更改了屬性的處理程序,而不用對屬性的設置程序做出反應,並且可以在該處理程序中對新值進行操作。 例如:

public string MyProperty
{
    get { return (string)GetValue(MyPropertyProperty); }
    set
    {
        SetValue(MyPropertyProperty, value);
    }
}

public static readonly DependencyProperty MyPropertyProperty =
  DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata(null, OnPropertyChanged));

private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if ((string)e.NewValue != (string)e.OldValue)
    {
        Debug.WriteLine(e.NewValue);
    }
}

如果要在UserControl使用綁定的字符串,則可以使用UserControl MyProperty 例如:

在您的UserControl

<UserControl Name="root" ...>
    <StackPanel>
        <TextBlock Text="{Binding MyProperty, ElementName=root}" />
    </StackPanel>
</UserControl> 

然后,當您使用<local:MyUserControl MyProperty="{Binding myString}"/> ,您的UserControl將顯示myString的值。

如果您使用c#命名約定-字段是駝峰式大小寫-則將這些內容綁定到字段( myString )。 沒用 您必須綁定到一個屬性(Pascalcase-get; set; ... etc)。 在這種情況下,您的輸出窗口中將出現綁定錯誤。

依賴項屬性的默認設置是OneWay綁定,這意味着如果usercontrol更改了不會反映在DataContext中的字符串。

將綁定更改為TwoWay

<local:MyUserControl MyProperty="{Binding myString, Mode=TwoWay}"/>      

或將DependencyProp更改為TwoWay模式:

DependencyProperty.Register("MyString", typeof(string), typeof(MyUserControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

暫無
暫無

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

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