簡體   English   中英

在WPF中使用依賴項屬性

[英]Using dependency properties in wpf

我不確定我是否正確掌握了這一點,我所閱讀的內容似乎與我正在嘗試的內容一致,但是似乎沒有用。

如果我將附加所有者添加到類的依賴項屬性中,則每當orig類dp更改時,更改應傳播到該附加所有者,對嗎?

我所擁有的是一個自定義控件,我要在該控件上設置一個屬性,然后在該自定義控件數據模板內的某些對象上繼承此屬性值。

public class Class1: DependencyObject{
  public static readonly DependencyProperty LongDayHeadersProperty;

  public bool LongDayHeaders {
     get { return (bool)GetValue(LongDayHeadersProperty); }
     set { SetValue(LongDayHeadersProperty, value); }
  }

  static Class1(){
    LongDayHeadersProperty = DependencyProperty.Register("LongDayHeaders", typeof(bool), typeof(Class1),
            new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits));
  }
}

public class Class2: DependecyObject{
  public static readonly DependencyProperty LongDayHeadersProperty;

  public bool LongDayHeaders{
    get{ return(bool)GetValue(LongDayHeadersProperty); }
    set{ SetValue(LongDayHeadersProperty, value); }
  }

  static Class2(){
    LongDayHeadersProperty = Class1.LongDayHeadersProperty.AddOwner(typeof(Class2));
  }
}

但是,如果我將DependencyPropertyDescriptor分配給這兩個屬性,則只會為Class1觸發,而Class2不會更改。

我是否錯過了我的理解范圍?

更新

經過一些測試,我什至不確定我的子控件是否被視為邏輯或可視樹中的子控件。 我認為是的,但是缺乏成功使我難以相信。

可觀察的class1集合中存在許多class2。 對我來說,這使他們成為1類的孩子嗎? 但是,即使我在class2上使用RegisterAttach,並在class1中設置了屬性,它似乎也沒有任何效果嗎?

MSDN所述,僅當您使用RegisterAttached創建屬性時,“ Inherits標志才起作用。 您仍然可以對屬性使用屬性語法。

更新資料

為了清楚起見,這是我將如何定義屬性:

public class Class1 : FrameworkElement
{
    public static readonly DependencyProperty LongDayHeadersProperty = 
        DependencyProperty.RegisterAttached("LongDayHeaders", 
        typeof(bool),
        typeof(Class1),
        new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits));

    public bool LongDayHeaders 
    {
        get { return (bool)GetValue(LongDayHeadersProperty); }
        set { SetValue(LongDayHeadersProperty, value); }
    }
}

public class Class2: FrameworkElement
{
    public static readonly DependencyProperty LongDayHeadersProperty = 
        Class1.LongDayHeadersProperty.AddOwner(typeof(Class2));

    public bool LongDayHeaders
    {
        get{ return(bool)GetValue(LongDayHeadersProperty); }
        set{ SetValue(LongDayHeadersProperty, value); }
    }
}

如果要讓子級成為控件的邏輯子級,則需要調用AddLogicalChild 另外,您應該通過LogicalChildren屬性公開它們。 我還必須指出,這兩個類都必須派生自FrameworkElementFrameworkContentElement ,因為僅為這些元素定義了邏輯樹。

由於您使用的是ObservableCollection ,因此您將處理集合更改的事件並根據更改添加/刪除子代。 同樣, LogicalChildren屬性可以只返回集合的枚舉數。

您將DependencyProperties與附加的(Dependency)屬性混淆了。

DP用於類希望自身具有可綁定,可樣式化等屬性的情況。 就像.NET屬性一樣,它們在它們的類之內。 您可以在單個對象上注冊屬性更改事件,但不能全局注冊。 TextBox.Text就是一個例子。 請注意, Label.TextTextBox.Text不相關。

當類要用其他屬性裝飾另一個對象時,AP適用於該類。 聲明AP的類能夠在具有此AP設置的其他對象的所有實例上偵聽屬性更改的事件。 Canvas.Left就是一個例子。 請注意,您始終必須限定此二傳手: <Label Text="Hi" Canvas.Left="50"/>

暫無
暫無

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

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