我有一个用户控件,其中包含Expander和其他一些控件。
用户控件具有自定义“XBackground”属性,该属性实际上仅为Expander设置背景。
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 :(得分:0)
轻微错误:
public static readonly DependencyProperty BcgProperty = DependencyProperty.Register(“XBackground”,typeof(Brush),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 ); }
}
答案 1 :(得分:0)
Register中的Owner类不是Expander,而是注册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));
答案 2 :(得分:0)
您不能使用typeof(Expander)
,而应使用UserControl的类型作为ownerType
方法的Register
参数。此外,您还必须在属性包装器中调用GetValue
和SetValue
。
除此之外,您还必须使用属性元数据注册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
的替代方法是将Expander的Background
属性绑定到XAML中UserControl的XBackground
属性:
<UserControl ...>
...
<Expander Background="{Binding XBackground,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
...
</UserControl>