WPF StackPanel 的拉伸

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13849325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:35:44  来源:igfitidea点击:

Stretching of WPF StackPanel

wpfbuttonuser-controlswpf-controlsstackpanel

提问by woodstock

I'm playing around with WPF and I'm trying to create an ImageButtoncontrol. I've created a UserControlas follows:

我正在玩 WPF 并且我正在尝试创建一个ImageButton控件。我创建了一个UserControl如下:

<UserControl
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         mc:Ignorable="d" 
         x:Class="WpfPractise.Controls.ImageButton"
         Height="auto" Width="auto" x:Name="ImageButtonControl">
<Button>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
        <Image Source="{Binding Image, ElementName=ImageButtonControl}"
               Width="16" Height="16"
           Margin="5,0,0,0" VerticalAlignment="Center"/>
        <TextBlock Text="{Binding Text, ElementName=ImageButtonControl}"
           Margin="5,0,0,0" VerticalAlignment="Center"/>
    </StackPanel>
</Button>

This is working fine except for the StackPanel doesn't stretch to fill the width or the height! I've tried a Grid in it's place but to no avail. Any ideas where I'm going wrong?

这工作正常,除了 StackPanel 不会拉伸以填充宽度或高度!我已经在它的位置尝试了网格,但无济于事。任何想法我哪里出错了?

Example:

例子:

Example

例子

回答by sa_ddam213

If you want to align the Buttoncontent to the left then you have to set the HorizontalContentAlignmentof the button

如果要将Button内容向左对齐,则必须设置HorizontalContentAlignment按钮的

   <Button HorizontalContentAlignment="Left" VerticalContentAlignment="Center">
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
            <Image Source="{Binding Image, ElementName=ImageButtonControl}"
           Width="16" Height="16"
       Margin="5,0,0,0" VerticalAlignment="Center"/>
            <TextBlock Text="{Binding Text, ElementName=ImageButtonControl}"
       Margin="5,0,0,0" VerticalAlignment="Center"/>
        </StackPanel>
    </Button>