ListBoxItem style in <ListBox.Resources> or in <ListBox.ItemContainerStyle>?

I can put haml Stylefor ListBoxItemin <ListBox.Resources>or in <ListBox.ItemContainerStyle>. See Code.
Question: what is the difference, what should I prefer?

<ListBox.Resources>
    <Style TargetType="ListBoxItem">
        <Setter Property="Canvas.Top" Value="{Binding Top}"/>
        <Setter Property="Canvas.Left" Value="{Binding Left}"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="Padding" Value="0"/>
    </Style>
</ListBox.Resources>

OR

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Canvas.Top" Value="{Binding Top}"/>
        <Setter Property="Canvas.Left" Value="{Binding Left}"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="Padding" Value="0"/>
    </Style>
</ListBox.ItemContainerStyle>

, , :
: "RelativeSource FindAncestor, AncestorType =" System.Windows.Controls.ItemsControl ", AncestorLevel = '1' '. BindingExpression: Path = HorizontalContentAlignment; DataItem = null.... ..
, - Aero , .
, !

+4
2

ItemContainerStyle - , wpf , . . .

ItemContainerStyle , WPF ListBox.Resources Window.Resources Application.Resources. .

+10

default Style, - Explicit style.

ListBoxItems, VisualTree ListBox.

<ListBox>
  <ListBox.Resources>
    <!-- default Style -->
  </ListBox.Resources>
  <ListBox.ItemTemplate>
     <DataTemplate>
        <ListBox>
           <ListBoxItem/> <-- Will be applied to this as well.
        </ListBox>
     </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

ListBoxItems, ListBox.

:

<Grid>
  <Grid.Resources>
     <Style x:Key="MyStyle" TargetType="ListBoxItem"/>
  </Grid.Resources>
  <ListBox ItemContainerStyle="{StaticResource MyStyle}"/>
</Grid>

, PresentationFramework.Aero.dll ILSpy, :

<Setter Property="HorizontalContentAlignment"
        Value="{Binding Path=HorizontalContentAlignment, 
         RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
<Setter Property="VerticalContentAlignment"
            Value="{Binding Path=VerticalContentAlignment,
         RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>

, , , , , , .

, , ItemContainerStyle, , ​​ - . , BasedOn x:Null.

<ListBox>
   <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem" BasedOn="{x:Null}"/>
   </ListBox.ItemContainerStyle>
</ListBox>
+6

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


All Articles