Reputation: 1560
I have an "ItemsControl" with 4 buttons, and when applying a margin, the first button does not look as I would like. Is it possible to modify the margin of the first button? Or, is it possible to access each button and apply different properties to it? Thank you
<ItemsControl ItemsSource="{Binding PercentageList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="{Binding PercentageList.Count}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Margin="5,0,0,0"
Content="{Binding Name}"
CommandParameter="{Binding}"
Style="{StaticResource ButtonStyle}"
Command="{Binding DataContext.SelectedPercentageCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
FINAL SOLUTION
<ItemsControl ItemsSource="{Binding PercentageList}"
AlternationCount="{Binding PercentageList.Count}">
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="FrameworkElement.Margin"
Value="5,5,0,5" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="{Binding PercentageList.Count}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"
CommandParameter="{Binding}"
Style="{StaticResource ButtonStyle}"
Command="{Binding DataContext.SelectedPercentageCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
<DataTemplate.Triggers>
<Trigger Property="ItemsControl.AlternationIndex"
Value="0">
<Setter Property="Margin"
Value="0,5" />
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Upvotes: 2
Views: 1260
Reputation: 1335
You could use a Trigger
to address this.
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}">
<Setter TargetName="myTargetElement" Property="SomeProperty" Value="SomeValue"/>
</DataTrigger>
</DataTemplate.Triggers>
This approach will let you customise properties in your DataTemplate
for the first item.
If you want to appy unique styles to each button, it sounds like you might need to capture more information in your button item viewmodels.
If you just want the spacing to be even around everything, I would normally use a half margin in all directions around my items, and use the complement around the ItemsControl
, which gets rid of these special snowflake cases.
Upvotes: 3
Reputation: 313
You can have a simpler approach, just change how you apply margin like this:
<Button Margin="2,0,0,2"
Content="{Binding Name}"
CommandParameter="{Binding}"
Style="{StaticResource ButtonStyle}"
Command="{Binding DataContext.SelectedPercentageCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}}" />
Upvotes: 0