wpf 以编程方式在按钮内添加图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15627123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:19:02  来源:igfitidea点击:

Adding an Image inside a Button programmatically

c#wpfbuttonchildren

提问by Wilson

In WPF:

在 WPF 中:

<Button Width="24" Height="24" >
    <Image Source="pack://application:,,,/res/x.png" VerticalAlignment="Center"/>
</Button>

How can I mimic this in C#? I can't find any method in the Buttonclass that adds children.

我怎样才能在 C# 中模仿这个?我在Button类中找不到任何添加子项的方法。

回答by sa_ddam213

Buttonis a Contentcontrol so you just have to use the ButtonsContentproperty

Button是一个Content控件,所以你只需要使用该ButtonsContent属性

Example:

例子:

Button myButton = new Button
{
    Width = 24,
    Height = 24,
    Content = new Image
    {
        Source = new BitmapImage(new Uri("image source")),
        VerticalAlignment = VerticalAlignment.Center
    }
};

回答by Jan

Why don't you add the Image in XAML and bind Sourceto a property in your view model?

为什么不在 XAML 中添加图像并绑定Source到视图模型中的属性?