【问题标题】:Change button's background image programmatically in a metro style app在 Metro 风格应用程序中以编程方式更改按钮的背景图像
【发布时间】:2012-08-11 21:14:00
【问题描述】:

如何使用 VS 2012 在 Metro Style 应用程序中更改按钮的背景图像? 在 Windows 窗体中,按钮具有可以设置的 BackgroundImage 属性。 此功能是否适用于 Metro Style 应用?

在 Windows 窗体中,我可以在 C# 中执行以下操作:

btnImage.BackgroundImage = System.Drawing.Image.FromFile("...\Pictures\flower.png");

如何以编程方式更改 Metro Style 应用程序中按钮的背景图像?

【问题讨论】:

    标签: xaml windows-8 microsoft-metro windows-runtime


    【解决方案1】:

    非常简单,实际上,只需修改 Button 的 XAML 以包含一个结束标记,并在其间放置一个图像控件,如下所示:

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Button HorizontalAlignment="Left" Margin="532,285,0,0" VerticalAlignment="Top" Height="135" Width="283">
            <Image Source="Assets/Logo.png" />
        </Button>
    </Grid>
    

    在上面的 sn-p 中,我将图像源指向 Logo.png 文件,该文件是 C#/XAML 应用程序内置模板的一部分。

    另一种方法是在 Blend for Visual Studio 中打开项目,将图像从 Assets 选项卡拖到设计图面上(确保在 Objects and Timeline 窗格中选择了所需的容器),然后向右- 单击图像并选择 Make into Control...,然后选择 Button 控件。

    此技术的唯一缺点是您无法获得内置 Button 控件所具有的默认 VisualStates。相反,Blend 使用空的 VisualStates 为您定义了一种样式,您可以根据需要设置样式。

    希望对您有所帮助。

    【讨论】:

    • 感谢您的快速回答:我会尝试一下。但是,例如,如何以编程方式更改 C# 中按钮的背景图像?例如。在某个事件中,将按钮的背景更改为另一个图像或将其删除(使其为空)?再次感谢。
    • Button.ImageSource = 设置这个。
    • @LeoLuis - 谢谢 - 我试过了,但它给了我一个错误:“Windows.UI.Xaml.Controls.Button 不包含'ImageSource'的定义......”不确定是什么指令我应该在这里使用。
    • 与 XAML 相同的方式 - 您可以设置 button.Content = new Image {ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/Logo.png"))} ; ...或者使用 ImageBrush - 例如button.Background = new ImageBrush {ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/Logo.png"))};
    • @FilipSkakun - 知道了。非常感谢大家!!!使用 System.Windows.Media.Imaging; button.Background = new ImageBrush {ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/Logo.png"))};
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    相关资源
    最近更新 更多