如何使用c#代码在Button中添加 StackPanel (即将以下XAML转换为C#)?没有Button.Children.Add
...
<Button>
<StackPanel Orientation="Horizontal" Margin="10">
<Image Source="foo.png"/>
</StackPanel>
</Button>
答案 0 :(得分:17)
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 :(得分:14)
设置Button.Content
而不是Button.Children.Add
作为一个较长的解释:
Content
。Children
的列表 - 例如StackPanel,Grid,WrapPanel,Canvas等。正如您的代码已经显示的那样,您可以将Button的Content
设置为Panel - 这样您就可以添加多个子控件了。但是,实际上在您的示例中,则不需要StackPanel和Image。看起来你的StackPanel只是添加了Padding - 如果你愿意,你可以将Padding添加到Image而不是StackPanel。
答案 2 :(得分:1)
像这样使用
<Window.Resources>
<ImageSource x:Key="LeftMenuBackgroundImage">index.jpg</ImageSource>
<ImageBrush x:Key="LeftMenuBackgroundImageBrush"
ImageSource="{DynamicResource LeftMenuBackgroundImage}"/>
</Window.Resources>
和Codebehind
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;
答案 3 :(得分:1)
在Xaml中:
<Button x:Name="Btn" Click="Btn_Click" Orientation="Horizontal" Margin="10">
<DockPanel>
<Image Source="foo.png" Height="16" Width="16"/>
</DockPanel>
</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")
};