I'm working with XAML/WPF in VS 2012. I'll admit I don't really understand templating and styling very well yet.
I've defined a style in my application.xaml file like this:
<Style x:Key="ContactGroups" TargetType="ListViewItem">
<!-- Styling omitted here -->
</Style>
Now I want to apply this style to my list view but I cannot figure out where to apply this styling, i.e., where to put the code to set the style. I've omitted lots of attributes here to keep things shorter:
<ListView ItemsSource="{Binding Groups}" SelectedItem="{Binding Path=SelectedGroup, Mode=OneWayToSource}" >
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="140" Height="25">
<Grid.RowDefinitions>
<RowDefinition Height="2*" />
</Grid.RowDefinitions>
<Label Content="{Binding Name}" ToolTip="{Binding Name}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Use StaticResource markup extension to set Style on ItemContainerStyle
of ListBox:
<ListView ItemsSource="{Binding Groups}"
SelectedItem="{Binding Path=SelectedGroup, Mode=OneWayToSource}"
ItemContainerStyle="{StaticResource ContactGroups}" >
I'm not sure if you only want this style to be applied to this list, but if not you could simply remove the x:Key="ContactGroups"
from the style and it should be applied to all list items.
If you are looking to only target this listview an option would be to add the style to the resources of the list view:
<ListView ItemsSource="{Binding Groups}" SelectedItem="{Binding Path=SelectedGroup, Mode=OneWayToSource}" >
<ListView.Resources>
<Style TargetType="ListViewItem">
<!-- Styling omitted here -->
</Style>
</ListView.Resources>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="140" Height="25">
<Grid.RowDefinitions>
<RowDefinition Height="2*" />
</Grid.RowDefinitions>
<Label Content="{Binding Name}" ToolTip="{Binding Name}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Edit: Based on your comment below this may be the approach you want to take:
<ListView.Resources>
<Style TargetType="ListViewItem" BasedOn="{StaticResource ContactGroups}" />
</ListView.Resources>
This way your style stays defined in the App.xaml.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With