使用XAML更改UserControl属性

时间:2012-09-01 10:14:31

标签: c# wpf xaml properties user-controls

我有UserControl

<UserControl x:Class="CustomCtrl.MyButton">
   <Button x:Name="Btn" />
</UserControl>

我在UserControl

中使用Window
<Window>
    <Grid>
        <MyButton Background="Aqua" />
    </Grid>
</Window>

我想使用我的Background 的属性Btn和XAML 更改按钮Background的{​​{1}}属性。

我尝试添加UserControl属性

Background

但它没有效果。
相反,如果我使用代码public class MyButton: UserControl { public new Brush Background { get { return Btn.GetValue(BackgroundProperty) as Brush; } set { Btn.SetValue(BackgroundProperty, value); } } } ,它就可以了 为什么?我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

<{1}} UserControl.Background不是自定义控件,您无法控制如何使用此属性。如果要更改一个控件的背景,可以公开新的依赖项属性并将其绑定到UserControls

答案 1 :(得分:0)

我认为你有两个选择:

  1. 简单的方法,只需将“Btn”背景设置为透明,如下所示:

    <UserControl x:Class="CustomCtrl.MyButton">
          <Button x:Name="Btn" Background="Transparent"/>
    </UserControl>
    
  2. 另一种方法是将按钮的背景颜色绑定到控件的背景颜色:

    <UserControl x:Class="CustomCtrl.MyButton" x:Name="control">
          <Button x:Name="Btn" Background="{Binding Background, ElementName=control}"/>
    </UserControl>
    
  3. 两者都经过测试,似乎有效。

答案 2 :(得分:0)

<Window>
    <Grid>
        <MyButton Background="Aqua" />
    </Grid>
</Window>

您正在设置UserControl的背景颜色。设置您必须的Button的背景颜色

<UserControl x:Class="CustomCtrl.MyButton">
   <Button x:Name="Btn" Background="Aqua" />
</UserControl>

编辑(OP评论后):您无法修改UserControl.Background,但新属性有效:

public Brush ButtonBackground {
    get {
        return this.Btn.Background;
    }
    set {
        this.Btn.Background = value;
    }
}

然后:

<Window>
    <Grid>
        <MyButton ButtonBackground="Aqua" />
    </Grid>
</Window>
相关问题