Switch ContentPresenter of ListBoxItem Based on Selection - wpf

I am trying to switch out the ContentPresenter of a ListBoxItem when it is selected, while using multiple DataTemplates to represent different types of data.
Here is the UserControl that defines the ListBox inside:
<UserControl x:Class="Homage.View.FilePanelView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vw="clr-namespace:Homage.View"
xmlns:vm="clr-namespace:Homage.ViewModel"
xmlns:ctrl="clr-namespace:Homage.Controls"
mc:Ignorable="d">
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:SlugViewModel}">
<vw:SlugView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:HeaderSlugViewModel}">
<vw:HeaderSlugView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:ContentSlugViewModel}">
<vw:ContentSlugView />
</DataTemplate>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Name="SlugContainer" Background="Transparent" BorderBrush="Black" BorderThickness="1" CornerRadius="2" Margin="0,5,0,0" Padding="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Content="{Binding DisplayName}" />
<ContentPresenter Grid.Row="1" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="SlugContainer" Property="BorderThickness" Value="5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid>
<ListBox ItemsSource="{Binding Slugs}" Padding="5" />
</Grid>
</UserControl>
Based on the type of data to be shown (e.g., a "Header Slug") a certain DataTemplate is applied to the ListBoxItem. This is working great, but I am wanting to adjust the DataTemplate of the selected ListBoxItem to a different DataTemplate -- again, based on the data type being shown.
The goal is that, because each data type is different, each would have a unique look when not selected and would receive a unique set of options when selected.
If I can get the above to work, that would be great! But, I also want to complicate things...
While each data type has unique controls they also have common controls. So I would ideally like to define all the common controls once so that they appear in the same place in the ListBox.
<DataTemplate x:Key="CommonSelectedTemplate">
<!-- common controls -->
...
<DataTemplate x:Key="UniqueSelectedTemplate">
<!-- all the unique controls -->
<ContentPresenter />
</DataTemplate>
<!-- more common controls -->
...
</DataTemplate>
If I have to define all the common stuff multiple times (for now) I'll live. =)
Thanks for any help!

Let's suppose that we have only two data types: Item1ViewModel and Item2ViewModel. Therefore we need 4 data templates: 2 for the common state, 2 for the selected state.
<DataTemplate x:Key="Template1" DataType="local:Item1ViewModel">
<TextBlock Text="{Binding Property1}" Foreground="Red" />
</DataTemplate>
<DataTemplate x:Key="Template2" DataType="local:Item2ViewModel">
<TextBlock Text="{Binding Property2}" Foreground="Blue" />
</DataTemplate>
<DataTemplate x:Key="Template1Selected" DataType="local:Item1ViewModel">
<TextBlock Text="{Binding Property1}" Background="Yellow" Foreground="Red" />
</DataTemplate>
<DataTemplate x:Key="Template2Selected" DataType="local:Item2ViewModel">
<TextBlock Text="{Binding Property2}" Background="Yellow" Foreground="Blue" />
</DataTemplate>
For switching the content between two templates based on different types I use the DataTemplateSelector class:
public class SampleTemplateSelector:DataTemplateSelector
{
public DataTemplate Type1Template { get; set; }
public DataTemplate Type2Template { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is Item1ViewModel)
return Type1Template;
else if (item is Item2ViewModel)
return Type2Template;
return null;
}
}
We need two instances of this selector: one for the common state and one for the selected state.
<local:SampleTemplateSelector x:Key="templateSelector"
Type1Template="{StaticResource Template1}"
Type2Template="{StaticResource Template2}"/>
<local:SampleTemplateSelector x:Key="selectedTemplateSelector"
Type1Template="{StaticResource Template1Selected}"
Type2Template="{StaticResource Template2Selected}"/>
And after that you should add this code which switches two selectors:
<DataTemplate x:Key="ListItemTemplate">
<ContentControl x:Name="content" Content="{Binding}" ContentTemplateSelector="{StaticResource templateSelector}" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="True">
<Setter TargetName="content" Property="ContentTemplateSelector" Value="{StaticResource selectedTemplateSelector}"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
That's all, apply this ItemTemplate to your ListBox without changing the ControlTemplate:
<ListBox ItemsSource="{Binding Items}" ItemTemplate="{StaticResource ListItemTemplate}" />

Related

Is it possible to change properties of a resource instantiated with StaticResource element in XAML?

With this piece of XAML:
<Window.Resources>
<Rectangle x:Key="rectangle" x:Shared="False" Width="20" Height="8" Fill="Red" />
</Window.Resources>
<StaticResource x:Name="r1" ResourceKey="rectangle" />
<StaticResource x:Name="r2" ResourceKey="rectangle" />
it is possible to assign a value to say, Margin property, to each instance independently by code:
r1.Margin = 2;
r2.Margin = 5;
Is it possible to do it directly in XAML? I tried:
<StaticResource ResourceKey="rectangle" Margin="3"/>
but Margin is not a property of StaticResource...
Rephrasing after the XY problem sensor fired (appropriately)!
I want to draw rectangles with exactly the same properties except one, e.g. the margin or the color, in order to be able to change the shared properties centrally and still be able to provide specific properties in XAML. Can I use a resource like in my attempt?
Adding my exact need and code as suggested by comments
My exact need is to show the effect of setting different properties to some rectangle, i.e. changing Rectangle.RenderTransformOrigin and Rectangle.RenderTransform to compare effects. It's indeed to learn WPF, not for a production application. At the moment, I use a style (rotated) as I wasn't able to use a resource (this is the reason of my question above).
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
Title="Transform Center" Height="400" Width="600">
<Window.Resources>
<Style x:Key="title" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Bottom" />
<Setter Property="Margin" Value="0,0,0,10" />
</Style>
<Style x:Key="rotated" TargetType="Rectangle">
<Setter Property="Width" Value="201" />
<Setter Property="Height" Value="81" />
<Setter Property="Fill" Value="CadetBlue"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
<Style x:Key="fixed" TargetType="Rectangle">
<Setter Property="Width" Value="30" />
<Setter Property="Height" Value="30" />
<Setter Property="Fill" Value="Indigo" />
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
</Window.Resources>
<Grid >
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Background="Beige" Margin="5">
<Rectangle Style="{StaticResource fixed}" />
<Rectangle Style="{StaticResource rotated}" />
</StackPanel>
<TextBlock Grid.Row="0" Grid.Column="0"
Style="{StaticResource title}" Text="No rotation" />
<StackPanel Grid.Row="0" Grid.Column="1" Background="Beige" Margin="5">
<Rectangle Style="{StaticResource fixed}" />
<Rectangle Style="{StaticResource rotated}">
<Rectangle.RenderTransformOrigin>.5,.5</Rectangle.RenderTransformOrigin>
<Rectangle.RenderTransform>
<RotateTransform Angle="20" />
</Rectangle.RenderTransform>
</Rectangle>
</StackPanel>
<TextBlock Grid.Row="0" Grid.Column="1"
Style="{StaticResource title}"
Text="RenderTransformOrigin" />
<StackPanel Grid.Row="1" Grid.Column="0" Background="Beige" Margin="5">
<Rectangle Style="{StaticResource fixed}" />
<Rectangle Style="{StaticResource rotated}">
<Rectangle.RenderTransform>
<RotateTransform Angle="20" CenterX="100" CenterY="40" />
</Rectangle.RenderTransform>
</Rectangle>
</StackPanel>
<TextBlock Grid.Row="1" Grid.Column="0"
Style="{StaticResource title}"
Text="RotateTransform Center" />
<!-- The center coordinates relative to the Rectangle are the sum
of both center coordinates, i.e. .5 + .5 = 1 (bottom-right corner) -->
<StackPanel Grid.Row="1" Grid.Column="1" Background="Beige" Margin="5">
<Rectangle Style="{StaticResource fixed}" />
<Rectangle Style="{StaticResource rotated}">
<Rectangle.RenderTransformOrigin>.5,.5</Rectangle.RenderTransformOrigin>
<Rectangle.RenderTransform>
<RotateTransform Angle="20" CenterX="100" CenterY="40" />
</Rectangle.RenderTransform>
</Rectangle>
</StackPanel>
<TextBlock Grid.Row="1" Grid.Column="1"
Style="{StaticResource title}"
Text="Both" />
</Grid>
</Window>
Does XAML allows to change a property of a resource when it is instantiated with <StaticResource>
Short answer: No.
The StaticResource markup extension simply references a resource based on a key. It can't change any properties of the resolved resource. You will have to set the properties of the resolved resource itself by for example casting the target property of the resource to a Rectangle.
I want to draw rectangles with exactly the same properties except one, e.g. the margin or the color
That sounds like a style to me. In WPF, there are usually several different ways to accomplish the same thing, and this is no exception.
it seems setting up a view-model is a bit oversized
Maybe. Maybe not. It's hard to say, as there aren't any other details in your question. That said, given the problem statement above, I'd agree it's certainly not necessary, and absent any other requirements, I don't see anything to be gained by using view models.
Even so, here's a code example that shows three different ways, two of which are based on view models and templates:
<Window x:Class="TestSO58683029RectStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:p="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:l="clr-namespace:TestSO58683029RectStyle"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<l:MainViewModel>
<l:MainViewModel.Rectangle1>
<l:RectangleViewModel Margin="2"/>
</l:MainViewModel.Rectangle1>
<l:MainViewModel.Rectangle2>
<l:RectangleViewModel Margin="5"/>
</l:MainViewModel.Rectangle2>
</l:MainViewModel>
</Window.DataContext>
<Window.Resources>
<p:Style TargetType="Rectangle">
<Setter Property="Width" Value="20"/>
<Setter Property="Height" Value="8"/>
<Setter Property="Fill" Value="Red"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</p:Style>
<DataTemplate DataType="{x:Type l:RectangleViewModel}">
<Rectangle Width="20" Height="8" Fill="Red" HorizontalAlignment="Left" Margin="{Binding Margin}"/>
</DataTemplate>
<x:Array x:Key="rectangleArray1" Type="{x:Type l:RectangleViewModel}">
<l:RectangleViewModel Margin="2"/>
<l:RectangleViewModel Margin="5"/>
</x:Array>
</Window.Resources>
<StackPanel>
<!-- Uses style -->
<Rectangle/>
<Rectangle Margin="2"/>
<Rectangle Margin="5"/>
<!-- Uses view models, individual properties -->
<ContentControl Content="{Binding Rectangle1}"/>
<ContentControl Content="{Binding Rectangle2}"/>
<!-- Uses view models, collection -->
<ItemsControl ItemsSource="{StaticResource rectangleArray1}"/>
</StackPanel>
</Window>
The view model approaches rely on these classes (they don't implement INotifyPropertyChanged, because there's no need in this simple example):
class RectangleViewModel
{
public Thickness Margin { get; set; }
}
class MainViewModel
{
public RectangleViewModel Rectangle1 { get; set; }
public RectangleViewModel Rectangle2 { get; set; }
}
As you can see, in the case of the style-based approach, a single <Style/> element in the resource dictionary can be used to define the default values for any properties you like. Then you can explicitly use a <Rectangle/> element where you want it in the content of your window, setting any other property explicitly. You can even override properties that were set in the style, if that's needed for any reason.
Note that in the above, the data template explicitly sets its property values. But you can actually combine the two techniques, by referring to the style resource when you declare the template, like so:
<DataTemplate DataType="{x:Type l:RectangleViewModel}">
<Rectangle Margin="{Binding Margin}" Style="{StaticResource ResourceKey={x:Type Rectangle}}"/>
</DataTemplate>
As noted in the comments, declaring concrete UI elements as resources is generally the wrong way to do something in WPF. I hesitate to say it's always wrong, but I would say it's almost always wrong. Concrete UI elements should be declared as actual content in the XAML, with styles used to provide default formatting for those elements. Otherwise you should be using templates, and allow WPF to create the UI elements as needed, based on the template you provide.

How to achieve the complex UI using ItemControl in silverlight

I am working on creating a complex report which almost looks like shown in here image
For this I have create a collection where I will store all the descriptions and its corresponding ratings.
This collection is then I am binding to a ItemControl. The collection will be fetched from database depending on criteria's.
Now my problem is how to fragment or separate single ItemControl to look like shown in image. Should I use multiple collections which will be then bind to different ItemControl ? Can I use multiple datagrids?
I am out of ideas... Any suggestions / examples much appreciated.
Definitely do-able. Treat each block (such as Mathmatics, Arts Education etc) as an item, and you're then just dealing with an ItemsCollection. Create a style for how to present each item in that collection, and another style for how to present each property in your block (which will also feature a collection of something.
An example I have of something similar, was blocks which consisted of a heading, and a varied number of checkboxes each with a description. There could be a varying number of these blocks too.
In my view, that displayed these blocks, my xaml looked something like this:
<ScrollViewer VerticalScrollBarVisibility="Visible" MaxHeight="100">
<ItemsControl ItemsSource="{Binding FeatureFlags, Mode=TwoWay}" Style="{StaticResource FlagGroupsAndFlagsItemsControlStyle}" />
</ScrollViewer>
I then had a style for that ItemsControl defined in a resource dictionary somewhere ...
<Style x:Key="FlagGroupsAndFlagsItemsControlStyle" TargetType="ItemsControl">
<Setter Property="Width" Value="Auto" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Grid x:Name="FlagListGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Width="{Binding Width, ElementName=FlagListGrid, Mode=OneWay}" IsReadOnly="True" Text="{Binding Name}" />
<ListBox Grid.Row="1" Width="{Binding Width, ElementName=FlagListGrid, Mode=OneWay}" ItemsSource="{Binding Flags}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
Style="{StaticResource FlagsListBoxItemsStyle}" Background="{Binding IsOptional, Converter={StaticResource YNToOptionalBackgroundColour}}"/>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
And then a style for the items within that templates ListBox ...
<Style x:Key="FlagsListBoxItemsStyle" TargetType="ListBox">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<toolkit:WrapPanel Width="{Binding Width, ElementName=FlagListGrid, Mode=OneWay}" Orientation="Horizontal" ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="20" Height="18" VerticalAlignment="Top" IsChecked="{Binding IsSelected, Mode=TwoWay}" />
<TextBlock Width="180" MinHeight="18" VerticalAlignment="Center" Text="{Binding Description}" TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
Unfortunately I can't show you an image of what the finished result looks like, but I hope these pointers could set you on track for your very similar problem

WPF ListBox Item collapse datatrigger not working

I have a listbox and all I want to do is collapse the listboxitem based on a boolean property of my SelectedItem.
The IsVisible property on my client Model implements the NotifyPropertyChanged event.
Overview - I have a list of clients which users can do CRUDs on. When they delete, I set a boolean property on the Model which my VM exposes to the View. This should then only hide the 'deleted' row from the list. During a flush to db I CRUD based on the mode of the model.
<ListBox Name="listClients"
Grid.Column="1" Grid.Row="1"
Margin="0" BorderThickness="0"
Height="auto"
Style="{StaticResource BumListBox}"
SelectionMode="Extended"
ItemsSource="{Binding Path=ClientList}"
SelectedItem="{Binding SelectedClient, Mode=TwoWay}"
Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" >
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsVisible}" Value="False">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding ClientNo}" Foreground="White" FontSize="{StaticResource HeaderFontSize}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Text="{Binding ClientDesc}" Foreground="White" FontSize="{StaticResource SubHeaderFontSize}" FontWeight="Light" VerticalAlignment="Center" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code behind to jippo MVVM process:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (_cvm.SelectedClient != null)
{
_cvm.SelectedClient.IsVisible = !_cvm.SelectedClient.IsVisible;
_cvm.CurrentSelectedIsVisible = _cvm.SelectedClient.IsVisible; //<- another option to bind to
}
}
I've tried the these suggestions here and here or something similar but I just can't get to hide the items.
Any help in the right direction would be great, cheers.
Edit
I've tried Blam's suggestion below like this but still unable to hide the items:
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Visibility" Value="{Binding Path=CurrentIsVisible, Converter={StaticResource b2v}}" />
</Style>
You will need to set up a converter if you are returning true/false but there is a system converter for that
Move it up to Resources
I have know I have used it this way
<ListBox x:Name="lb" ItemsSource="{Binding}" DisplayMemberPath="Text">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Visibility" Value="{Binding Path=Vis}" />
</Style>
</ListBox.Resources>
</ListBox>
This was rather frustrating and the solution so simple. My client model with IsVisible is in a dll and the NotifyPropertyChanged() changes were never built to update the reference in my project..so the binding never happened. These late nights are taking their toll.

Need multiple styles dependent on Listboxitem

i have a Listbox, which stores two different object types, based on the same baseclass. (e.g. BaseObject = baseclass and the children of it: CustomPath and CustomImage)
The Datasource:
ObservableCollection<BattlegroundBaseObject> _baseObjectCollection;
public ObservableCollection<BattlegroundBaseObject> BaseObjectCollection
{
get { return _baseObjectCollection?? (_baseObjectCollection= new ObservableCollection<BaseObject>()); }
}
The Listbox databinding: <ListBox ItemsSource="{Binding BaseObjectCollection}"
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" x:Name="ListBoxPathLineStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem" x:Name="BattlegroundObjectControlTemplate">
<Path Stroke="{Binding ObjectColor}" StrokeThickness="{Binding StrokeThickness}" Data="{Binding PathGeometryData}" x:Name="PathLine" Opacity="{Binding Opacity}">
</Path>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Effect" TargetName="PathLine">
<Setter.Value>
<DropShadowEffect Color="CornflowerBlue" ShadowDepth="3" BlurRadius="10" />
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
I want to add to the ControlTemplate where the Path is, also a Image and to differ it by type or a property. doesnt matter.
anyone any ideas?
You can add to ListBox resources DataTemplate for each type.
In my example classes Car and Motorbike derived from Vehicle class.
<ListBox x:Name="listBox">
<ListBox.Resources>
<DataTemplate DataType="{x:Type local:Car}">
<StackPanel Background="Red">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Motorbike}">
<StackPanel Background="Orange">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.Resources>
</ListBox>
EDIT:
You can add style for ListBoxItem to resources:
<ListBox x:Name="listBox">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect Color="CornflowerBlue" ShadowDepth="3" BlurRadius="10" />
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
<DataTemplate DataType="{x:Type local:Car}">
<StackPanel Background="Red">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Motorbike}">
<StackPanel Background="Orange">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.Resources>
</ListBox>
You could define some DataTemplates for your different classes. They determine how the classes are displayed. I've been using them to display derived classes differently when working with a collection of the base class.
<DataTemplate DataType="{x:Type CustomPath}">
<TextBlock Text="This is a CustomPath"/>
</DataTemplate>
<DataTemplate DataType="{x:Type CustomImage}">
<TextBlock Text="This is a CustomImage"/>
</DataTemplate>
At the moment you are changing the style of the controls that WPF is using to render your bound data. A better way to do this is to provide WPF with a way of generating the correct controls. Ignore the ListBoxItem and use DataTemplates for your actual objects.
First you need to tell the Window or control how to find your types.
<Window or UserControl
...
xmlns:model="clr-namespace:yourNamespace"
>
Then you can provide WPF with a way to show your objects e.g.
<DataTemplate TargetType="{x:Type model:CustomPath}">
<Path Stroke="{Binding ObjectColor}" StrokeThickness="{Binding StrokeThickness}"
Data="{Binding PathGeometryData}" x:Name="PathLine" Opacity="{Binding Opacity}"/>
<!-- maybe use a binding from the Path.Effect back to the IsSelected and ValueConverters
to re-apply the selection effect-->
</DataTemplate>
<DataTemplate TargetType="{x:Type model:CustomImage}">
<Image Src="{Binding SomeProperty}" />
</DataTemplate>
Now all you need to do is to make these available to the ListBox in some way. Almost every element in WPF can have .Resources added to it, so you could choose to do these across the entire window
<Window ...>
<Window.Resources>
<DataTemplate .../>
<DataTemplate .../>
</Window.Resources>
...
<ListBox .../>
</Window>
or you can apply it more locally
<Window ...>
...
<ListBox>
<ListBox.Resources>
<DataTemplate .../>
<DataTemplate .../>
</ListBox.Resources>
</ListBox>
</Window>
And this way your listbox definition can become much neater too, e.g. if you are using Window.Resources
<ListBox ItemsSource="{Binding BaseObjectCollection}"/>

Silverlight vs WPF - Treeview with HierarchialDataTemplate

So, the following is easy enough in WPF, but how would you do it in Silverlight?
Please note that the trick here is to display both Groups, and Entries on the same level.
Additonally you dont know how deep the entries are nested, they might be on the first, or the nth level.
This is hard in Silverlight because you lack the DataType="{x:Type local:Group}" property in the H.DataTemplate (or any DataTemplate). Building my own custom DataTempalteSelector also didnt work, because the Hierarchial ItemsSource gets lost. (Which just gave me a new idea which I will investigate shortly)
Example:
Group1
--Entry
--Entry
Group2
--Group4
----Group1
------Entry
------Entry
----Entry
----Entry
--Entry
--Entry
Group3
--Entry
--Entry
Your Classes:
public class Entry
{
public int Key { get; set; }
public string Name { get; set; }
}
public class Group
{
public int Key { get; set; }
public string Name { get; set; }
public IList<Group> SubGroups { get; set; }
public IList<Entry> Entries { get; set; }
}
Your xaml:
<TreeView Name="GroupView" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Group}" ItemsSource={Binding Items}">
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:Entry}" >
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</TreeView.Resources>
</TreeView>
The TreeView control from the Silverlight toolkit supports hierarchical data templates.
Check out this article for sample usage, but it looks identical to me to the WPF built in one.
You can download the Silverlight toolkit here.
Here is an example of using the HierarchicalDataTemplate with a HeaderedItemsControl in Silverlight (Songhay.Silverlight.BiggestBox.Views.ClientView.xaml):
<UserControl x:Class="Songhay.Silverlight.BiggestBox.Views.ClientView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
xmlns:sdk="clr-namespace:System.Windows;assembly=System.Windows.Controls"
xmlns:sdkctrls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
xmlns:uriMapper="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"
xmlns:v="clr-namespace:Songhay.Silverlight.BiggestBox.Views"
xmlns:m="clr-namespace:Songhay.Silverlight.BiggestBox.ViewModels">
<UserControl.Resources>
<Style x:Key="StackPanelRoot" TargetType="StackPanel">
<Setter Property="Background" Value="Seashell" />
<Setter Property="Height" Value="598" />
<Setter Property="Width" Value="1024" />
</Style>
<Style x:Key="GridRoot" TargetType="Grid">
<Setter Property="Height" Value="570" />
</Style>
<Style x:Key="ClientGridSplitter" TargetType="sdkctrls:GridSplitter">
<Setter Property="Background" Value="#FFE0EEE0" />
<Setter Property="Height" Value="8" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
<m:ClientViewModel x:Key="ClientViewModelDataSource" d:IsDataSource="True"/>
<Style TargetType="sdkctrls:HeaderedItemsControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="sdkctrls:HeaderedItemsControl">
<StackPanel>
<ItemsPresenter Margin="10,0,0,0" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ScrollViewerIndexItems" TargetType="ScrollViewer">
<Setter Property="Margin" Value="10" />
<Setter Property="VerticalScrollBarVisibility" Value="Auto" />
</Style>
<Style x:Key="StackPanelIndexItems" TargetType="StackPanel">
<Setter Property="Background" Value="#ff9" />
<Setter Property="Orientation" Value="Horizontal" />
</Style>
</UserControl.Resources>
<UserControl.DataContext>
<Binding Source="{StaticResource ClientViewModelDataSource}"/>
</UserControl.DataContext>
<Border BorderBrush="Black" BorderThickness="1" VerticalAlignment="Center">
<StackPanel x:Name="RootPanel" Style="{StaticResource StackPanelRoot}">
<Grid Style="{StaticResource GridRoot}">
<Grid.RowDefinitions>
<RowDefinition MinHeight="128" MaxHeight="360" Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="1.5*" />
</Grid.RowDefinitions>
<v:HeaderView Grid.Row="0" />
<sdkctrls:GridSplitter Grid.Row="1" Style="{StaticResource ClientGridSplitter}" />
<StackPanel Grid.Row="2"
Orientation="Horizontal"
Style="{StaticResource StackPanelIndexItems}">
<ScrollViewer Style="{StaticResource ScrollViewerIndexItems}">
<sdkctrls:HeaderedItemsControl
Header="{Binding IndexTitle}"
ItemsSource="{Binding Outlines}">
<sdkctrls:HeaderedItemsControl.HeaderTemplate>
<DataTemplate>
<TextBlock FontSize="24" FontWeight="Bold" Text="{Binding}" />
</DataTemplate>
</sdkctrls:HeaderedItemsControl.HeaderTemplate>
<sdkctrls:HeaderedItemsControl.ItemTemplate>
<sdk:HierarchicalDataTemplate>
<StackPanel>
<TextBlock FontSize="12" FontWeight="Bold" Margin="0,10,0,0" Text="{Binding Text}" />
<sdkctrls:HeaderedItemsControl ItemsSource="{Binding Outlines}" Margin="10,0,10,0">
<sdkctrls:HeaderedItemsControl.ItemTemplate>
<sdk:HierarchicalDataTemplate>
<HyperlinkButton
ClickMode="Press"
Command="{Binding IndexItemCommand, Source={StaticResource ClientViewModelDataSource}}"
CommandParameter="{Binding Url}"
FontSize="12">
<HyperlinkButton.Content>
<TextBlock Text="{Binding Text}" />
</HyperlinkButton.Content>
</HyperlinkButton>
</sdk:HierarchicalDataTemplate>
</sdkctrls:HeaderedItemsControl.ItemTemplate>
</sdkctrls:HeaderedItemsControl>
</StackPanel>
</sdk:HierarchicalDataTemplate>
</sdkctrls:HeaderedItemsControl.ItemTemplate>
</sdkctrls:HeaderedItemsControl>
</ScrollViewer>
<navigation:Frame x:Name="IndexFrame" Width="685">
</navigation:Frame>
</StackPanel>
</Grid>
<v:FooterView Height="30" />
</StackPanel>
</Border>
</UserControl>

Resources