C# 如何在C代码隐藏中的按钮中添加StackPanel

C# 如何在C代码隐藏中的按钮中添加StackPanel,c#,wpf,xaml,button,C#,Wpf,Xaml,Button,如何使用c#代码隐藏(即将以下XAML转换为c#)在按钮中添加堆栈面板?没有按钮。儿童。添加 <Button> <StackPanel Orientation="Horizontal" Margin="10"> <Image Source="foo.png"/> </StackPanel> </Button> 设置按钮。内容而不是使用按钮。子项。添加 作为一个较长的解释: 按钮是一个“只有一个子项”的控件,它

如何使用c#代码隐藏(即将以下XAML转换为c#)在按钮中添加堆栈面板?没有
按钮。儿童。添加

<Button>
   <StackPanel Orientation="Horizontal" Margin="10">
      <Image Source="foo.png"/>
   </StackPanel>
</Button>

设置
按钮。内容
而不是使用
按钮。子项。添加

作为一个较长的解释:

  • 按钮是一个“只有一个子项”的控件,它的
    内容
  • 只有极少数控件(通常为“面板”)可以包含零个或更多子控件的列表,例如StackPanel、Grid、WrapPanel、Canvas等

正如您的代码所示,您可以将按钮的
内容设置为面板-这将允许您添加多个子控件。但是,在您的示例中,实际上不需要StackPanel和图像。看起来StackPanel只是在添加填充,如果愿意,您可以将填充添加到图像而不是StackPanel。

这样使用

  Image img = new Image();
  img.Source = new BitmapImage(new Uri("foo.png"));

  StackPanel stackPnl = new StackPanel();
  stackPnl.Orientation = Orientation.Horizontal;
  stackPnl.Margin = new Thickness(10);
  stackPnl.Children.Add(img);

  Button btn = new Button();
  btn.Content = stackPnl;
<Window.Resources>   
    <ImageSource x:Key="LeftMenuBackgroundImage">index.jpg</ImageSource>
    <ImageBrush x:Key="LeftMenuBackgroundImageBrush" 
     ImageSource="{DynamicResource LeftMenuBackgroundImage}"/> 
</Window.Resources>
在Xaml中:

<Button x:Name="Btn" Click="Btn_Click" Orientation="Horizontal" Margin="10">
  <StackPanel>
     <Image Source="foo.png" Height="16" Width="16"/>
  </StackPanel>
</Button>
我建议您将图像放在xaml参考资料中:

<Window.Resources>
    <BitmapImage x:Key="Img" UriSource="/Img/foo.png"/>
</Window.Resources>
Button btn = new Button();
StackPanel panel = new StackPanel();
Image img = new Image
{
   Source = "../foo.png"
}
panel.Children.Add(img);
btn.Content = panel;
<Window.Resources>
    <BitmapImage x:Key="Img" UriSource="/Img/foo.png"/>
</Window.Resources>
Image img = new Image
{
   Source = (BitmapImage)FindResource("Img")
};