1

我有我的UserControl

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

我用我UserControlWindow

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

我想使用带有 XAML的 my的属性来更改BackgroundButtonBtn的属性。BackgroundUserControl

我尝试添加Background属性

public class MyButton: UserControl
{
    public new Brush Background
    {
        get
        { return Btn.GetValue(BackgroundProperty) as Brush; }

        set
        { Btn.SetValue(BackgroundProperty, value); }
    }        
}

但它没有效果。
相反,如果我使用代码MyButtonControl.Background = Brushes.Aqua;,它可以工作。
为什么?我该如何解决这个问题?

4

3 回答 3

1

istakeUserControl.Background不是自定义控件,您无法控制如何使用此属性UserControls如果您只想更改一个控件的背景,您可以公开一个新的依赖属性并将其绑定到Button.Background.

于 2012-09-01T14:06:08.877 回答
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>
    

两者都进行了测试,似乎有效。

于 2012-09-01T10:57:46.320 回答
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>
于 2012-09-01T10:58:30.923 回答