2016-07-05 240 views
0

我有一個用戶控件,其中包含擴展器和其他一些控件。WPF自定義屬性的動態值

用戶控件有一個自定義的「XBackground」屬性,它實際上只爲擴展器設置背景。

public Brush XBackground 
    { 
     get 
     { 
      return expander.Background; 
     } 
     set 
     { 
      expander.Background = value; 
     } 
    } 

當我使用我的用戶控件時,背景只能靜態設置,而不是動態設置。調試器說只有DependencyProperty可以通過動態資源設置。在這裏,我卡住了。我試圖在我的XBackground屬性上註冊依賴項屬性,但是我收到一個錯誤,提示「只能在DependencyObject的DependencyProperty上設置」DynamicResourceExtension「。」

這是我的註冊依賴屬性的嘗試:

public static readonly DependencyProperty BcgProperty = DependencyProperty.Register("XBackground", typeof(Brush), typeof(Expander)); 

回答

0

不得使用typeof(Expander),而是你的用戶控件作爲Register方法的ownerType參數的類型。此外,您還必須在屬性包裝中調用GetValueSetValue

除此之外,你也必須一PropertyChangedCallback與屬性的元數據寄存器,以收到通知屬性值變化:

public partial class YourUserControl : UserControl 
{ 
    ... 

    public Brush XBackground 
    { 
     get { return (Brush)GetValue(XBackgroundProperty); } 
     set { SetValue(XBackgroundProperty, value); } 
    } 

    public static readonly DependencyProperty XBackgroundProperty = 
     DependencyProperty.Register(
      "XBackground", 
      typeof(Brush), 
      typeof(YourUserControl), 
      new PropertyMetadata(null, XBackgroundPropertyChanged)); 

    private static void XBackgroundPropertyChanged(
     DependencyObject obj, DependencyPropertyChangedEventArgs e) 
    { 
     var userControl = (YourUserControl)obj; 
     userControl.expander.Background = (Brush)e.NewValue; 
    } 
} 

PropertyChangedCallback另一種方法是結合了擴展的Background屬性將用戶控件在XAML XBackground屬性:

<UserControl ...> 
    ... 
    <Expander Background="{Binding XBackground, 
     RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/> 
    ... 
</UserControl> 
+0

是的!我不知道如何從'XBackgroundPropertyChanged'內部訪問我的控件,謝謝! – Adder

0

小的失誤:

公共靜態只讀的DependencyProperty BcgProperty = DependencyProperty.Register( 「XBackground」 的typeof(刷)的typeof(YourCustomUserControl));

完整版:

public static readonly DependencyProperty XBackgroundProperty 
      = DependencyProperty.Register("XBackground", typeof(Brush), typeof(YourCustomUserControl)); 
public Brush XBackground 
{ 
    get { return (Brush) GetValue(XBackgroundProperty); } 
    set { SetValue(XBackgroundProperty, value); } 
} 
0

所有者類註冊是不是一個擴展,但在你的DependencyProperty註冊的類的名稱。 試試這個:

public Brush XBackground 
    { 
     get { return (Brush)GetValue(XBackgroundProperty); } 
     set { SetValue(XBackgroundProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for XBackground. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty XBackgroundProperty = 
     DependencyProperty.Register("XBackground", typeof(Brush), typeof(/typeof your UserControl goes here/), new PropertyMetadata(null)); 
+0

好了,錯誤已經一去不復返了,但現在我的控制是透明的,顏色不適用。 – Adder

+1

顯示你的xaml,它看起來像你沒有正確設置綁定源 – bakala12

+0

源應該沒問題,它適用於所有其他預設屬性。 'XBackground =「{DynamicResource ResourceKey = bcgResource}」' – Adder