You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在代码中为动态创建的ListBox应用样式?

Got it, let's break down how to apply styles to those dynamically created ListBoxes in your scenario. Since you're using ObservableCollection<Person>, I'm assuming you're working with WPF (the approach is nearly identical for UWP with minor tweaks). Here are the most practical and maintainable methods:


This is the cleanest approach—separating your style logic from your C# code makes it easier to maintain and reuse styles across your app.

First, define your style in your Window/UserControl's XAML resources:

<Window.Resources>
    <!-- Style for the ListBox itself -->
    <Style x:Key="GroupListBoxStyle" TargetType="ListBox">
        <Setter Property="Background" Value="#F5F5F5"/>
        <Setter Property="BorderBrush" Value="#D0D0D0"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Padding" Value="6"/>
        <Setter Property="Margin" Value="8"/>
        <Setter Property="Width" Value="250"/>
        
        <!-- Optional: Style for individual ListBoxItems -->
        <Setter Property="ItemContainerStyle">
            <Setter.Value>
                <Style TargetType="ListBoxItem">
                    <Setter Property="Margin" Value="2"/>
                    <Setter Property="Padding" Value="4"/>
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="#2563EB"/>
                            <Setter Property="Foreground" Value="White"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#E2E8F0"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

Then, reference this style when creating your ListBoxes in code:

foreach (var group in yourGroupsFromDatabase)
{
    // Create the ListBox instance
    var groupListBox = new ListBox();
    
    // Apply the style from XAML resources
    groupListBox.Style = (Style)FindResource("GroupListBoxStyle");
    
    // Populate with your ObservableCollection<Person>
    var peopleInGroup = GetPeopleForGroup(group.Id); // Your DB fetch logic
    groupListBox.ItemsSource = peopleInGroup;
    
    // Add a header to identify the group (optional but helpful)
    groupListBox.Header = $"{group.Name} ({peopleInGroup.Count} members)";
    
    // Add the ListBox to your panel
    pnl.Children.Add(groupListBox);
}

2. Define Styles Directly in Code

If you prefer to keep all logic in C# (not recommended for complex styles), you can build the style inline:

foreach (var group in yourGroupsFromDatabase)
{
    var groupListBox = new ListBox();
    
    // Build the ListBox style
    var listBoxStyle = new Style(typeof(ListBox));
    listBoxStyle.Setters.Add(new Setter(ListBox.BackgroundProperty, Brushes.LightGray));
    listBoxStyle.Setters.Add(new Setter(ListBox.BorderBrushProperty, Brushes.DarkGray));
    listBoxStyle.Setters.Add(new Setter(ListBox.BorderThicknessProperty, new Thickness(1)));
    
    // Build the ListBoxItem style with triggers
    var itemStyle = new Style(typeof(ListBoxItem));
    itemStyle.Setters.Add(new Setter(ListBoxItem.MarginProperty, new Thickness(2)));
    
    var selectedTrigger = new Trigger
    {
        Property = ListBoxItem.IsSelectedProperty,
        Value = true
    };
    selectedTrigger.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, Brushes.DodgerBlue));
    selectedTrigger.Setters.Add(new Setter(ListBoxItem.ForegroundProperty, Brushes.White));
    itemStyle.Triggers.Add(selectedTrigger);
    
    listBoxStyle.Setters.Add(new Setter(ListBox.ItemContainerStyleProperty, itemStyle));
    
    // Assign the style to the ListBox
    groupListBox.Style = listBoxStyle;
    
    // Populate and add to panel
    groupListBox.ItemsSource = GetPeopleForGroup(group.Id);
    groupListBox.Header = group.Name;
    pnl.Children.Add(groupListBox);
}

3. Apply a Global Default Style

If you want every ListBox (including dynamically created ones) to automatically use the same style, omit the x:Key in your XAML style:

<Window.Resources>
    <Style TargetType="ListBox">
        <!-- Same setters as the first example -->
    </Style>
</Window.Resources>

Now all ListBoxes in your window will adopt this style without any extra code—perfect for consistent UI across your app.


Bonus: Customize Person Item Display

To make each Person entry look more polished (e.g., show name + job title), add a DataTemplate to your XAML resources and link it to the style:

<Window.Resources>
    <DataTemplate x:Key="PersonItemTemplate" DataType="{x:Type local:Person}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FullName}" FontWeight="SemiBold"/>
            <TextBlock Text=" | " Foreground="Gray"/>
            <TextBlock Text="{Binding JobTitle}" Foreground="#666666"/>
        </StackPanel>
    </DataTemplate>

    <Style x:Key="GroupListBoxStyle" TargetType="ListBox">
        <Setter Property="ItemTemplate" Value="{StaticResource PersonItemTemplate}"/>
        <!-- Other setters -->
    </Style>
</Window.Resources>

内容的提问来源于stack exchange,提问作者SezMe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:09:09