Windows运行时:如何在椭圆形状按钮中设置图像
本文关键字:按钮 设置 图像 椭圆形 运行时 Windows | 更新日期: 2023-09-27 18:00:23
<Button x:Name="btnProfilePicture" HorizontalAlignment="Center" Click="btnProfilePicture_Click">
<Button.Template>
<ControlTemplate>
<Ellipse x:Name="ellipsePicture" Fill="Turquoise" Width="150" Height="150" Stroke="White" StrokeThickness="10">
</Ellipse>
</ControlTemplate>
</Button.Template>
</Button >
我有一个椭圆形状的按钮,默认颜色填充。我想在运行时将填充更改为代码隐藏中的图像。
我该怎么做?
更多信息:我试图使用"ellipsePicture"名称来设置椭圆填充,但这个名称在后面的代码中无法引用,但我不知道原因。
尝试以下代码。。
<Button x:Name="BtnProfilePicture" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10">
<Button.Template>
<ControlTemplate>
<Grid Height="100">
<Ellipse x:Name="ellipsePicture" Fill="{TemplateBinding Background}"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button >
在代码后面添加以下行。。
BtnProfilePicture.BackgroundImage =
new ImageBrush { ImageSource = LoadBackgroundImage(yourfilename.jpg)};
如果可行,请投票给我!
试试这个:
<Button x:Name="btnProfilePicture" HorizontalAlignment="Center" Click="btnProfilePicture_Click">
<Button.Template>
<ControlTemplate>
<Ellipse x:Name="ellipsePicture" Width="150" Height="150" Stroke="White" StrokeThickness="10">
<Ellipse.Fill>
<ImageBrush ImageSource="/DessCol;component/Images/Recommencer.ico"/>
</Ellipse.Fill>
</Ellipse>
</ControlTemplate>
</Button.Template>
您可以使用按钮的Background属性在背景上设置图像。你可以从代码后面使用它,也可以像:
public BitmapImage LoadBackgroundImage(string fileName)
{
var image = new BitmapImage();
try
{
image.BeginInit();
if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
{
var bytes = File.ReadAllBytes(fileName);
image.StreamSource = new MemoryStream(bytes);
}
else
{
var bytes = File.ReadAllBytes(Path.GetFullPath(Properties.Resources.DefaultBackgroundImage));
image.StreamSource = new MemoryStream(bytes);
}
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();
image.Freeze();
}
catch (FileNotFoundException ex)
{
throw ex;
}
return image;
}
在您的按钮点击事件中添加以下行
btnPilePicture.Background=LoadBackgroundImage(yourfilename.jpg(;//您可以使用.jpg、.jpeg、*.png
试试吧。修改后,您可以将图像设置为内容。这些更改可以在XAML和运行时进行。
<Button Content="C:'Round.JPG">
<Button.Template>
<ControlTemplate>
<Ellipse x:Name="ellipsePicture" Width="150" Height="150" Stroke="White" StrokeThickness="10">
<Ellipse.Fill>
<ImageBrush ImageSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type Button}},
Path=Content}"/>
</Ellipse.Fill>
</Ellipse>
</ControlTemplate>
</Button.Template>
</Button>