设置按钮背景

时间:2014-06-01 12:25:19

标签: c# wpf

我制作了圈子作为我的按钮。但我如何通过代码更改图像

<Button Style="{StaticResource myStyle}" Name="Prj_Button" Content="Button" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="180" Height="180" Click="Prj_Button_Click">
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <Ellipse>
                        <Ellipse.Fill>
                            <ImageBrush ImageSource="/Presentation Interface;component/Images/pic1.png"/>
                        </Ellipse.Fill>
                    </Ellipse>
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>

1 个答案:

答案 0 :(得分:3)

如果您想在代码中执行此操作,则需要通过ImageBrush查找Button.Template并首先执行此操作,然后您需要为ImageBrush提供一些名称

<ImageBrush x:Name="imgBackground" ... />

然后在代码中您可以使用FindName

var ib = Prj_Button.Template.FindName("imgBackground", Prj_Button) as ImageBrush;
ib.ImageSource = new BitmapImage(...);

Button此时必须已加载,因此您可以在Window.Loaded事件或稍后的某个地方执行此操作。如果您在Window构造函数中执行此操作(例如

),它将无法工作

修改

但我建议使用TemplateBinding并将Ellipse.Fill绑定到Button.Background

<Button Name="Prj_Button" Content="Button" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="180" Height="180">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Grid>
                <Ellipse Fill="{TemplateBinding Background}"/>
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>

然后你可以用代码

Prj_Button.Background = new ImageBrush(new BitmapImage(...));