2011-03-22 82 views
12

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

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

回答

13

Button.Content,而不是使用Button.Children.Add

至於更詳細的解釋:

  • 按鈕是 「唯一的有1個小孩」 的控制 - 其Content
  • 只有極少數的控件(通常是「面板」)可以包含零個或多個的列表Children - 例如StackPanel中,網格,WrapPanel,帆布等

當你的代碼已經具備了,你可以設置一個按鈕Content是一個面板 - 這將EHN允許你再添加多個子控件。但是,真的在你的例子中,那麼就沒有必要像StackPanel那樣擁有StackPanel了。看起來你的StackPanel只是添加了Padding,並且你可以添加Padding到圖片,而不是添加到StackPanel。

15
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; 
1

使用這樣

<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; 
相關問題