ProgramingTip

선택한 ListBox 항목의 배경색 변경

bestdevel 2020. 12. 2. 21:43
반응형

선택한 ListBox 항목의 배경색 변경


이것은 지금까지 내 XAML입니다.

    <ScrollViewer Grid.Column="1" Grid.RowSpan="2">

        <ListBox   Background="Black" ItemsSource="{Binding Path=ActiveLog}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Background="Black">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="200"></ColumnDefinition>
                            <ColumnDefinition Width="*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition></RowDefinition>
                            <RowDefinition></RowDefinition>
                        </Grid.RowDefinitions>
                        <TextBlock Grid.Column="0" Grid.Row="0" Foreground="White">
                            <TextBlock >Date:</TextBlock>
                            <TextBlock  Text="{Binding Path=LogDate}"/>
                        </TextBlock>
                        <TextBlock Grid.Column="1" Grid.Row="0" Foreground="White">
                            <TextBlock >Severity:</TextBlock>
                            <TextBlock  Text="{Binding Path=Severity}"/>
                        </TextBlock>
                        <TextBlock Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Foreground="LightGray" Text="{Binding Path=Message}"></TextBlock>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.Template>
                <ControlTemplate>
                    <StackPanel Background="Black" IsItemsHost="True" >
                    </StackPanel>
                </ControlTemplate>
            </ListBox.Template>

        </ListBox>
    </ScrollViewer>

유일한 문제는 선택한 항목의 오른쪽에 파란색 상자가되는 것입니다. 선택 색상을 사용하지 못합니다.


ListBox.ItemContainerStyle 을 사용 합니다.

ListBox.ItemTemplate 은 항목 내용 이 표시되는 방법을 지정합니다 . 그러나 WPF는 여전히 각 항목을 ListBoxItem 컨트롤로 래핑합니다.이 컨트롤은 기본적으로 배경이 선택 시스템 강조 표시 색상으로 설정됩니다. WPF에서 ListBoxItem 컨트롤을 만드는 것을 중지 할 수는 없지만 스타일을 색 수 있습니다 (귀하의 경우 배경을 항상 투명 또는 검은 색 등으로 설정). 그렇게 비용이 많이 드는 ItemContainerStyle을 사용합니다.

juFo의 답변 은 항목 스타일의 많은 내에서 시스템 배경 리소스를 "하이재킹"하여 가능한 구현을 보여줍니다. 아마도 더 관용적 인 또 다른 기술은 Setter배경 속성에 를 사용하는 것 입니다.


<UserControl.Resources>
    <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Transparent"/>
        </Style.Resources>
    </Style>
</UserControl.Resources> 

<ListBox ItemsSource="{Binding Path=FirstNames}"
         ItemContainerStyle="{StaticResource myLBStyle}">  

listboxitem의 스타일을 재정의하기 만하면됩니다 (참조 : TargetType은 ListBoxItem 임).


또는 HighlightBrushKey를 ListBox에서 직접 적용 할 수 있습니다. Setter Property = "Background"Value = "Transparent"가 작동하지 않는 것이 있습니다. 하지만 Foreground를 Black으로 설정해야합니다.

    <ListBox  ... >
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True" >
                        <Setter Property="FontWeight" Value="Bold" />
                        <Setter Property="Background" Value="Transparent" />
                        <Setter Property="Foreground" Value="Black" />
                    </Trigger>
                </Style.Triggers>
                <Style.Resources>
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
                </Style.Resources>
            </Style>                
        </ListBox.ItemContainerStyle>

선택 스타일을 모두 지정해야합니다. HighlightBrushKey와 ControlBrushKey를 설정해야합니다. 포커스 포커스가있는 동안 투명한 HighlightBrusKey를 사용합니다. Bt, 컨트롤이 포커스를 잃는 경우 (아직 강조 표시되어있는 동안) ControlBrushKey를 사용합니다.

<Style.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>

.Net 4.5 이상을 사용 InactiveSelectionHighlightBrushKey하는 경우 다음 대신 사용하십시오 ControlBrushKey.

<Style.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</Style.Resources>

이것이 누군가를 돕기를 바랍니다.


선택이 중요하지 않은 경우 ScrollViewer에 래핑 된 ItemsControl을 사용하는 것이 좋습니다. 이 조합은 Listbox (실제로 이미 ItemsControl에서 파생 됨)보다 더 가볍고이를 사용하면 ItemsControl에 이미없는 동작을 재정의하기 위해 값싼 해킹을 사용할 필요가 없습니다.

선택 동작이 실제로 중요한 경우에는 분명히 작동하지 않습니다. 그러나 사용자가 볼 수없는 방식으로 선택한 항목 배경의 색상을 변경하려는 경우 혼란 스러울뿐입니다. 항목이 선택되었음을 나타 내기 위해 다른 특성을 변경하려는 경우이 질문에 대한 다른 답변 중 일부가 여전히 더 관련성이있을 수 있습니다.

다음은 마크 업이 어떻게 보이는지에 대한 골격입니다.

    <ScrollViewer>
        <ItemsControl>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    ...
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>

이와 같은 항목 선택을위한 새 템플릿을 만들어야합니다.

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="ListBoxItem">
            <Border
                BorderThickness="{TemplateBinding Border.BorderThickness}"
                Padding="{TemplateBinding Control.Padding}"
                BorderBrush="{TemplateBinding Border.BorderBrush}"
                Background="{TemplateBinding Panel.Background}"
                SnapsToDevicePixels="True">
                <ContentPresenter
                    Content="{TemplateBinding ContentControl.Content}"
                    ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
                    HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                    VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
                    SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

참고 URL : https://stackoverflow.com/questions/2138200/change-background-color-for-selected-listbox-item

반응형