Reputation: 19033
To split into group i have the following code in xaml:
<ListView x:Name="lvPallets" ItemsSource="{Binding Entries}">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<Image Source="{Binding Image}"/>
<TextBlock Text="{Binding Name}" Margin="5,5,5,5" VerticalAlignment="Center" />
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Name}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
To actually split into groups i added x:Name
attribute and some code in code behind file:
public SimulationWindow()
{
InitializeComponent();
_viewModel = new SimulationWindowViewModel();
DataContext = _viewModel;
lvPallets.Loaded += foo;
}
void foo(object sender, EventArgs e)
{
CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(lvPallets.ItemsSource);
PropertyGroupDescription groupDescription = new PropertyGroupDescription("Group");
view.GroupDescriptions.Add(groupDescription);
}
I would like to remove x:Name
attribute and function foo
. How can i do it?
Upvotes: 0
Views: 921
Reputation: 1201
It is possible to define a CollectionViewSource
in the XAML
, simply define it in the Resources
of the parent and use it via x:Key
.
<!-- Define CollectionViewSource -->
<Parent.Resources>
<CollectionViewSource x:Key="GroupCVS" Source="{Binding Entries}">
<!-- Group by the Property 'Group' -->
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Group" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Parent.Resources>
<!-- use the CollectionViewSource -->
<ListView ItemsSource="{Binding Source={StaticResource GroupCVS}}">
Note: I haven't found a way to declare the CollectionViewSource
directly in the ListView
due it must be known before applied (-> StaticResource
).
Upvotes: 5