Can I get a ListBox WPF to inherit brushes from a parent element?

My WPF window has a foreground brush installed on the brush from the resource dictionary, and I want all the text in the window to have this color, so I don’t touch the foreground brush with anything else.

Text fields get color Text blocks get color Buttons get color

The list does not receive color, so their contents are not saved.

Is there a way to make Listbox behave like other controls in this regard?

Assuming not, and what is design, what’s the point?

Edit:

It seems my question is not clear enough.

I understand how to create styles and resources and apply them to ListBoxes; I am wondering why I need to do this for certain controls, when I do not need for others - why some inherit properties and others do not - and is there a way to make them all inheritable the same way.

+3
source share
3 answers

, ListBox Foreground, , Setter . , ListBox, Foreground, , .

:

# 6 , WPF # 7.

+8

:

<Style x:Key="{x:Type ListBoxItem}" TargetType="ListBoxItem">
  <Setter Property="SnapsToDevicePixels" Value="true"/>
  <Setter Property="OverridesDefaultStyle" Value="true"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="ListBoxItem">
        <Border 
          Name="Border"
          Padding="2"
          SnapsToDevicePixels="true">
          <ContentPresenter />
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="true">
            <Setter TargetName="Border" Property="Background"
                    Value="{StaticResource SelectedBackgroundBrush}"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Foreground"
                    Value="{StaticResource DisabledForegroundBrush}"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

, , , "DisabledForegroundBrush" . Window.Resource, .

+1

You can do something like this:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="root">
    <ListBox>
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBox}">
                <Style.Resources>
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Yellow"/>
                    <SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}" Color="Red"/>
                </Style.Resources>
            </Style>
        </ListBox.Resources>
        <ListBoxItem>Item 1</ListBoxItem>
        <ListBoxItem>Item 2</ListBoxItem>
    </ListBox>
</Page>

Instead, Color="Red"you can use the Binding expression to bind to a color resource defined for your application.

+1
source

Source: https://habr.com/ru/post/1736661/


All Articles