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

C# 以编程方式在按钮内添加图像,c#,wpf,button,children,C#,Wpf,Button,Children,在WPF中: 我如何在C#中模仿这个?我在按钮类中找不到任何添加子项的方法。为什么不在XAML中添加图像并将源绑定到视图模型中的属性?按钮是一个内容控件,因此您只需使用按钮内容属性即可 例如: <Button Width="24" Height="24" > <Image Source="pack://application:,,,/res/x.png" VerticalAlignment="Center"/> </Button> 如果我想将图像

在WPF中:



我如何在C#中模仿这个?我在
按钮
类中找不到任何添加子项的方法。

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

按钮
是一个
内容
控件,因此您只需使用
按钮
内容
属性即可

例如:

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

如果我想将图像添加到包含文本内容的按钮,该怎么办?
Button myButton = new Button
{
    Width = 24,
    Height = 24,
    Content = new Image
    {
        Source = new BitmapImage(new Uri("image source")),
        VerticalAlignment = VerticalAlignment.Center
    }
};