簡體   English   中英

如何在 C# 代碼后面的按鈕中添加 StackPanel

[英]How to add a StackPanel in a Button in C# code behind

如何使用后面的 c# 代碼在 Button 中添加StackPanel (即將以下 XAML 轉換為 C#)? 沒有Button.Children.Add ...

<Button>
   <StackPanel Orientation="Horizontal" Margin="10">
      <Image Source="foo.png"/>
   </StackPanel>
</Button>
  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;

設置Button.Content而不是使用Button.Children.Add

作為更長的解釋:

  • Button 是一個“只有一個孩子”的控件 - 它的Content
  • 只有很少的控件(通常是“面板”)可以包含零個或多Children項的列表 - 例如 StackPanel、Grid、WrapPanel、Canvas 等。

正如您的代碼已經顯示的那樣,您可以將按鈕的Content設置為面板 - 這將允許您添加多個子控件。 但是,實際上在您的示例中,不需要 StackPanel 和 Image。 您的 StackPanel 似乎只添加了 Padding - 如果您願意,可以將 Padding 添加到圖像而不是 StackPanel。

像這樣使用

<Window.Resources>   
    <ImageSource x:Key="LeftMenuBackgroundImage">index.jpg</ImageSource>
    <ImageBrush x:Key="LeftMenuBackgroundImageBrush" 
     ImageSource="{DynamicResource LeftMenuBackgroundImage}"/> 
</Window.Resources>

在代碼隱藏中

Button btn = new Button();
        btn.HorizontalContentAlignment = HorizontalAlignment.Stretch;
        btn.VerticalContentAlignment = VerticalAlignment.Stretch;
        StackPanel stk = new StackPanel();
        stk.Orientation = Orientation.Horizontal;
        stk.Margin = new Thickness(10, 10, 10, 10);
        stk.SetResourceReference(StackPanel.BackgroundProperty, "LeftMenuBackgroundImageBrush");
        btn.Content = stk;

在 Xaml 中:

<Button x:Name="Btn" Click="Btn_Click" Orientation="Horizontal" Margin="10">
  <StackPanel>
     <Image Source="foo.png" Height="16" Width="16"/>
  </StackPanel>
</Button>

在 C# 中:

Button btn = new Button();
StackPanel panel = new StackPanel();
Image img = new Image
{
   Source = "../foo.png"
}
panel.Children.Add(img);
btn.Content = panel;

我建議你把圖像放在 xaml 資源中:

<Window.Resources>
    <BitmapImage x:Key="Img" UriSource="/Img/foo.png"/>
</Window.Resources>

並這樣稱呼它:

Image img = new Image
{
   Source = (BitmapImage)FindResource("Img")
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM