2016-07-05 116 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