【问题标题】:Put buttons inside ListBox that will stretch to it's width将按钮放在 ListBox 内,将拉伸到它的宽度
【发布时间】:2010-06-11 16:07:05
【问题描述】:

我想创建按钮列表,并且我希望按钮分布在列表项空间中。这是我所拥有的:

    <ListBox Margin="44,54,134,0" Name="listView1" Height="64" >
        <Button Height="20"></Button>
        <Button Height="20"></Button>            
    </ListBox>

结果是:

alt text http://img251.imageshack.us/img251/4050/samplec.png

第一张照片

我想要第二张图片之类的东西,但按钮的右侧要粘在列表的右侧。我尝试在 ItemTemplate 中绑定到 ListBox 宽度,但这不适用于所有情况(如果宽度为 Auto)

谢谢, 安德烈

【问题讨论】:

    标签: .net wpf


    【解决方案1】:
    <ListBox Margin="44,54,134,0" Name="listView1" Height="64" HorizontalContentAlignment="Stretch">
        <Button Height="20"></Button>
        <Button Height="20"></Button>
    </ListBox>
    

    编辑来自 Andrey

    如果您希望此解决方案完美,请添加以下行:

            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Padding" Value="0"></Setter>
                </Style>
            </ListBox.ItemContainerStyle>
    

    他们将消除左侧令人讨厌的间隙,使列表不对称

    【讨论】:

    • 如果你愿意,也可以给按钮控件加一个margin,可以左右调整间距;您可以使用负边距来补偿 ListBoxItem 容器中的填充,而无需重新设置容器的样式。缺点是您必须对每个按钮应用边距。
    【解决方案2】:

    这是我设法解决这个问题的方法。这更灵活,但对于这样一个简单的任务来说确实是开销

        <ListBox ItemsSource="{Binding}">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                                <Grid>
                                    <Button Height="20">
                                        <ContentPresenter></ContentPresenter>
                                    </Button>
                                </Grid>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"></TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 2012-02-04
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 2010-10-24
      相关资源
      最近更新 更多