jeudi 2 octobre 2014

Change from Window to UserControl


Vote count:

0




I am having some styles defined for list view. The style appear will depends on the data whether it is first level or second level (using expander). In order to define it, a class of GroupItemStyleSelector has been created. Unfortunately it throw an exception of null reference of Window.


Since my xaml file is created with <UserControl>, how can I change the code of GroupItemStyleSelector to avoid error? I have tried to use this and UserControl. But it couldn't locate the Style.


The codes are refer from online materials.


xaml



<local:GroupItemStyleSelector x:Key="groupItemStyleSelector" />
<!-- Style for the first level GroupItem -->
<Style x:Key="FirstLevel" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" FontWeight="Bold" VerticalAlignment="Bottom" />
<TextBlock Text="{Binding ItemCount}" Foreground="Silver" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
<TextBlock Text=" item(s)" Foreground="Silver" FontStyle="Italic" VerticalAlignment="Bottom" />
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Style for the second level GroupItem -->
<Style x:Key="SecondLevel" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" Margin="15,0,0,0">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" FontWeight="Bold" VerticalAlignment="Bottom" />
<TextBlock Text="{Binding ItemCount}" Foreground="Silver" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
<TextBlock Text=" item(s)" Foreground="Silver" FontStyle="Italic" VerticalAlignment="Bottom" />
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


cs



public class GroupItemStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
Style s;

CollectionViewGroup group = item as CollectionViewGroup;
Window window = Application.Current.MainWindow;

if (!group.IsBottomLevel)
{
s = window.FindResource("FirstLevel") as Style;
}
else
{
s = window.FindResource("SecondLevel") as Style;
}

return s;
}
}


asked 17 secs ago







Change from Window to UserControl

Aucun commentaire:

Enregistrer un commentaire