簡體   English   中英

WPF依賴屬性不起作用

[英]WPF Dependency Property not working

我有一個定義的依賴屬性定義如下:

public static readonly DependencyProperty MyDependencyProperty =
DependencyProperty.Register(
"MyCustomProperty", typeof(string), typeof(MyClass));

    private string _myProperty;
    public string MyCustomProperty
    {
        get { return (string)GetValue(MyDependencyProperty); }
        set
        {
            SetValue(MyDependencyProperty, value);
        }
    }

現在我嘗試在XAML中設置該屬性

<controls:TargetCatalogControl MyCustomProperty="Boo" />

但是DependencyObject中的setter永遠不會被擊中! 雖然我將屬性更改為常規屬性而不是Dep Prop

試試這個..

    public string MyCustomProperty
    {
        get 
        { 
            return (string)GetValue(MyCustomPropertyProperty); 
        }
        set 
        { 
            SetValue(MyCustomPropertyProperty, value); 
        }
    }

    // Using a DependencyProperty as the backing store for MyCustomProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyCustomPropertyProperty =
        DependencyProperty.Register("MyCustomProperty", typeof(string), typeof(TargetCatalogControl), new UIPropertyMetadata(MyPropertyChangedHandler));


    public static void MyPropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        // Get instance of current control from sender
        // and property value from e.NewValue

        // Set public property on TaregtCatalogControl, e.g.
        ((TargetCatalogControl)sender).LabelText = e.NewValue.ToString();
    }

    // Example public property of control
    public string LabelText
    {
        get { return label1.Content.ToString(); }
        set { label1.Content = value; }
    }

它沒有,除非你手動調用它。 有一個屬性更改的處理程序,您可以添加到DependancyProperty構造函數調用,以通知屬性何時更改。

調用此構造函數:

http://msdn.microsoft.com/en-us/library/ms597502.aspx

使用此構造函數創建的PropertyMetadata實例:

http://msdn.microsoft.com/en-us/library/ms557327.aspx

編輯:此外,您沒有正確實現依賴屬性。 你的getset應分別使用GetValueSetValue ,你不應該有一個類成員來存儲值。 在DP的成員名字也應該是{PropertyName}Property ,如MyCustomPropertyProperty如果get / set的注冊和屬性名是MyCustomProperty 有關更多信息,請參見http://msdn.microsoft.com/en-us/library/ms753358.aspx

希望有所幫助。

也許您正在使用MVVM,並覆蓋View的DataContext?

如果這樣做,那么更改MyCustomProperty的事件將在原始 DataContext上引發,而不是在新的ViewModel上引發。

暫無
暫無

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

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