我制作了圈子作为我的按钮。但我如何通过代码更改图像
<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>
答案 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(...));