如何在WPF中调整列表视图中图像的宽度?

时间:2019-04-30 12:59:25

标签: c# wpf xaml listview

我有一个ListView,其中包含Image作为项目。每当我调整包含它的网格的大小时,我都希望每个图像的宽度都跟随ListView的宽度。

<!--Playlists-->
<Grid Column="0">
    <ListView Grid.Row="1" Grid.Column="1"
              HorizontalAlignment="Stretch"
              ... >

        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListView.ItemContainerStyle>

        <!--Images-->
        <ListView.ItemTemplate>
            <DataTemplate DataType="{x:Type models:PlaylistModel}">
                <Grid HorizontalAlignment="Stretch">
                    <Image Source="{Binding ImagePath}"
                           Stretch="Uniform">
                    </Image>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>

    </ListView>
</Grid>

<GridSplitter Grid.Column="0" />

来源:http://www.teixeira-soft.com/bluescreen/2016/03/21/c-how-to-make-a-panel-within-a-datatemplate-fill-the-entire-width-of-a-listview-or-itenscontrol-derivative/

This is what happens

如此处所示,图像的宽度根本不会调整大小。即使ListView的大小更改,图像大小也保持不变。但是,如果我在Grid内设置DataTemplate的宽度,则Image实际上将遵循该宽度。

1 个答案:

答案 0 :(得分:0)

使用ListView似乎是一个错误。将所有内容更改为ListBox可以为我解决。

如果有人遇到相同的问题,请留在这里。

<ListBox HorizontalAlignment="Stretch">

    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListBox.ItemContainerStyle>

    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type models:PlaylistModel}">
            <Image Source="{Binding ImagePath}"
                       Stretch="Uniform" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>