C#WPF更改列表框项目大小

时间:2015-09-07 17:35:59

标签: c# wpf

我想创建地铁风格列表框。我需要Listboxitem的XAML样式代码。我想改变Listboxİtem大小运行时。

1 个答案:

答案 0 :(得分:-1)

您可以使用样式。将以下XAML添加到窗口:

<Grid>
    <ListBox Name="MyListBox" DisplayMemberPath="ItemText">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="Height" Value="{Binding ItemHeight}"/>
                <Setter Property="Width" Value="{Binding ItemWidth}"/>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</Grid>

在后面的代码中,通过将一些数据项绑定到列表框来填充列表,如下所示:

    public class ItemData
    {
        public int ItemHeight { get; private set; }
        public int ItemWidth { get; private set; }
        public string ItemText { get; private set; }
        public ItemData(int itemHeight, int itemWidth, string itemText)
        {
            ItemHeight = itemHeight;
            ItemWidth = itemWidth;
            ItemText = itemText;
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        MyListBox.ItemsSource = BuildItems();
    }

    private System.Collections.IEnumerable BuildItems()
    {
        yield return new ItemData(20, 200, "First");
        yield return new ItemData(40, 300, "Second");
        yield return new ItemData(60, 100, "Third");
    }

当您运行应用程序时,您会看到不同的项目具有不同的大小。