GoogleImages-like listbox with detail panel - wpf

How would you design a Google images -like component?
I'm not sure how to handle the detail panel which shows under each image when selected.
The detail panel:
- shows between two rows of images.
- keep left and right items in place.
SOLUTION:
Thanks to LittleBit for providing a very nice solution to the problem. Based on his hints, i created the following general-purpose component taking care of a few details you will eventually face when making LittleBit solution production-ready.
file: DetailedList.cs
public class DetailedList : ListBox
{
#region DetailsTemplate
public DataTemplate DetailsTemplate
{
get { return (DataTemplate)GetValue( DetailsTemplateProperty ); }
set { SetValue( DetailsTemplateProperty, value ); }
}
public static readonly DependencyProperty DetailsTemplateProperty =
DependencyProperty.Register( nameof( DetailsTemplate ), typeof( DataTemplate ), typeof( DetailedList ) );
#endregion
static DetailedList()
{
Type ownerType = typeof( DetailedList );
DefaultStyleKeyProperty.OverrideMetadata( ownerType,
new FrameworkPropertyMetadata( ownerType ) );
StyleProperty.OverrideMetadata( ownerType,
new FrameworkPropertyMetadata( null, ( depObj, baseValue ) =>
{
var element = depObj as FrameworkElement;
if( element != null && baseValue == null )
baseValue = element.TryFindResource( ownerType );
return baseValue;
} ) );
}
}
file: StretchGrid.cs
internal class StretchGrid : Grid
{
private Expander _expander;
#region ParentPanel
public Panel ParentPanel
{
get { return (Panel)this.GetValue( ParentPanelProperty ); }
set { this.SetValue( ParentPanelProperty, value ); }
}
public static readonly DependencyProperty ParentPanelProperty = DependencyProperty.Register(
nameof( ParentPanel ), typeof( Panel ), typeof( StretchGrid ), new PropertyMetadata( null, ParentPanelChanged ) );
private static void ParentPanelChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
var stretchGrid = d as StretchGrid;
if( stretchGrid == null ) return;
if( e.NewValue is Panel panel )
panel.SizeChanged += stretchGrid.UpdateMargins;
}
#endregion
public StretchGrid()
{
this.Loaded += StretchGrid_Loaded;
}
private void StretchGrid_Loaded( object sender, RoutedEventArgs e )
{
_expander = this.FindLogicalParent<Expander>();
_expander.Expanded += UpdateMargins;
_expander.SizeChanged += UpdateMargins;
this.UpdateMargins( null, null );
}
private void UpdateMargins( object sender, RoutedEventArgs e )
{
if( ParentPanel == null ) return;
if( _expander == null ) return;
Point delta = _expander.TranslatePoint( new Point( 0d, 0d ), ParentPanel );
//Create negative Margin to allow the Grid to be rendered outside of the Boundaries (full row under the item)
this.Margin = new Thickness( -delta.X, 0, delta.X + _expander.ActualWidth - ParentPanel.ActualWidth, 0 );
}
}
file: DetailedList.xaml
<Style x:Key="{x:Type cc:DetailedList}" TargetType="{x:Type cc:DetailedList}"
BasedOn="{StaticResource {x:Type ListBox}}">
<Style.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="NoButtonExpander.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Style.Resources>
<Setter Property="Grid.IsSharedSizeScope" Value="True"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="SelectionMode" Value="Single"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel Width="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type cc:DetailedList}}}"
Tag="{Binding RelativeSource={RelativeSource Self}}" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Name="Border" SnapsToDevicePixels="True">
<Expander Style="{StaticResource NoButtonExpander}" VerticalAlignment="Top"
IsExpanded="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"
Width="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}">
<Expander.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition SharedSizeGroup="A"/>
</Grid.RowDefinitions>
<ContentPresenter Grid.Row="0"/>
</Grid>
</Expander.Header>
<cc:StretchGrid ParentWrapPanel="{Binding Path=Tag,
RelativeSource={RelativeSource AncestorType={x:Type WrapPanel}}}">
<ContentPresenter ContentTemplate="{Binding DetailsTemplate,
RelativeSource={RelativeSource AncestorType={x:Type cc:DetailedList}}}"/>
</cc:StretchGrid>
</Expander>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Border" Property="Background"
Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
file: NoButtonExpander.xaml
<Style x:Key="ExpanderRightHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Padding="{TemplateBinding Padding}">
<Grid Background="Transparent" SnapsToDevicePixels="False">
<ContentPresenter HorizontalAlignment="Center" Margin="0,4,0,0" Grid.Row="1" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Top"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ExpanderUpHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Padding="{TemplateBinding Padding}">
<Grid Background="Transparent" SnapsToDevicePixels="False">
<ContentPresenter Grid.Column="1" HorizontalAlignment="Left" Margin="4,0,0,0" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Center"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ExpanderLeftHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Padding="{TemplateBinding Padding}">
<Grid Background="Transparent" SnapsToDevicePixels="False">
<ContentPresenter HorizontalAlignment="Center" Margin="0,4,0,0" Grid.Row="1" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Top"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ExpanderHeaderFocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Border>
<Rectangle Margin="0" SnapsToDevicePixels="true" Stroke="Black" StrokeThickness="1" StrokeDashArray="1 2"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ExpanderDownHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Padding="{TemplateBinding Padding}">
<Grid Background="Transparent" SnapsToDevicePixels="False">
<ContentPresenter Grid.Column="1" HorizontalAlignment="Left" Margin="4,0,0,0" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Center"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="NoButtonExpander" TargetType="{x:Type Expander}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Expander}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="3" SnapsToDevicePixels="true">
<DockPanel>
<ToggleButton x:Name="HeaderSite" ContentTemplate="{TemplateBinding HeaderTemplate}" ContentTemplateSelector="{TemplateBinding HeaderTemplateSelector}" Content="{TemplateBinding Header}" DockPanel.Dock="Top" Foreground="{TemplateBinding Foreground}" FontWeight="{TemplateBinding FontWeight}" FocusVisualStyle="{StaticResource ExpanderHeaderFocusVisual}" FontStyle="{TemplateBinding FontStyle}" FontStretch="{TemplateBinding FontStretch}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsChecked="{Binding IsExpanded, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Margin="1" MinWidth="0" MinHeight="0" Padding="{TemplateBinding Padding}" Style="{StaticResource ExpanderDownHeaderStyle}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
<ContentPresenter x:Name="ExpandSite" DockPanel.Dock="Bottom" Focusable="false" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" Visibility="Collapsed" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</DockPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsExpanded" Value="true">
<Setter Property="Visibility" TargetName="ExpandSite" Value="Visible"/>
</Trigger>
<Trigger Property="ExpandDirection" Value="Right">
<Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Right"/>
<Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Left"/>
<Setter Property="Style" TargetName="HeaderSite" Value="{StaticResource ExpanderRightHeaderStyle}"/>
</Trigger>
<Trigger Property="ExpandDirection" Value="Up">
<Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Top"/>
<Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Bottom"/>
<Setter Property="Style" TargetName="HeaderSite" Value="{StaticResource ExpanderUpHeaderStyle}"/>
</Trigger>
<Trigger Property="ExpandDirection" Value="Left">
<Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Left"/>
<Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Right"/>
<Setter Property="Style" TargetName="HeaderSite" Value="{StaticResource ExpanderLeftHeaderStyle}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

My approach is to use a ListView with some modifications
The ItemsPanel of the ListView must have a 'wrap' function, so i used a Wrappanel to display the Image-Previews in a field.
The ItemContainter of the ListViewItem must have two states. An Image-Preview state and a Detail-View therfore an Expander should do the trick.
The Details of an Image must be displayed across the whole Column under the Image. We need something which renders outside the Boundaries of a ListViewItem (more later)
It now looks like this
The Image Details are now messed up due to the Boundaries. The Height is no problem because it just moves the next Column down until it fits in. The Problem is the Width and its Position (its not left aligned).
I created a small CustomControl, the StretchGrid which renders its Content across the whole Column and left aligned. This StretchGrid get the relative distance to the left Boundary and sets it as negative Margin.Left to render it properly. Now it looks like this (and i hope that is exactly what you are looking for).
Now the Style of the ListView
<!-- Image List with Detail -->
<Style x:Key="PicList" TargetType="{x:Type ListView}">
<!-- Only one Picture can be selected -->
<Setter Property="SelectionMode" Value="Single"/>
<!-- Enable Multi-Line with a WrapPanel Around the Items -->
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel Width="{Binding (ListView.ActualWidth),RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}" Tag="{Binding RelativeSource={RelativeSource Self}}" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<!-- Override Display area of the Item -->
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListViewItem}">
<!-- Define Image Item -->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<!-- Use Expander Header as Preview/Thumbnail and display Details below when expanded -->
<Expander x:Name="PicThumbnail" Style="{StaticResource NoButtonExpander}" IsExpanded="{Binding (ListViewItem.IsSelected), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}" Width="{Binding (ListViewItem.ActualWidth), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}">
<Expander.Header>
<!-- Thumbnail/Preview Section -->
<StackPanel>
<Image Source="/XAML;component/Assets/Images/Thumb.png" Height="16" Width="16" />
<Label Content="{Binding Name}"/>
</StackPanel>
</Expander.Header>
<!-- Self stretching Grid (Custom Control) -->
<cc:StretchGrid x:Name="PicDetails" Background="LightGray" ParentWrappanel="{Binding Path=Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type WrapPanel}}}">
<!-- Picture Detail Section (quick & dirty designed, replace later) -->
<Image ClipToBounds="False" Source="/XAML;component/Assets/Images/Highres.png" Width="128" Height="128" HorizontalAlignment="Left" Margin="10,0" />
<Rectangle Fill="Black" Height="128" Width="5" HorizontalAlignment="Left"/>
<Rectangle Fill="Black" Height="128" Width="5" HorizontalAlignment="Right"/>
<StackPanel Margin="150,0">
<Label Content="{Binding Name}"/>
<Label Content="Description: Lorem"/>
<Label Content="Category: Ipsum"/>
<Label Content="Owner: Dolor"/>
<Label Content="Size: 5kB"/>
</StackPanel>
</cc:StretchGrid>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
<!-- Brings selected element to front, details see edit -->
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="1" />
</Trigger>
</Style.Triggers>
</Style>
</Setter.Value>
</Setter>
</Style>
Note: Its necessary to add a Reference to the StretchGrid.
And the StretchGrid Custom Control
class StretchGrid : Grid
{
//Reference for parent expander (used to calculate Grid Margin)
private Expander m_expander;
//Property for relativesource Binding to Wrappanel in Style
public WrapPanel ParentWrappanel
{
get { return (WrapPanel)this.GetValue(Wrappanel); }
set { this.SetValue(Wrappanel, value); }
}
//DependencyProperty for RelativeSource Binding to Wrappanel in Style (Note: the Binding is set inside the Style, not here programmatically in PropertyMetaData)
public static readonly DependencyProperty Wrappanel = DependencyProperty.Register("ParentWrappanel", typeof(WrapPanel), typeof(StretchGrid), new PropertyMetadata(null));
//Constructor
public StretchGrid() : base()
{
Application.Current.MainWindow.Loaded += Init;
Application.Current.MainWindow.SizeChanged += UpdateMargins;
}
private void Init(object sender, RoutedEventArgs e)
{
m_expander = (Expander)this.Parent; //Change when xaml markup hirarchy changes
if(m_expander != null) //(or make it similar to the Wrappanel with
{ //RelativeSource Binding)
m_expander.Expanded += UpdateMargins; //Update when expander is expanded
m_expander.SizeChanged += UpdateMargins; //Update when the expander changes the Size
//Update all StretchGrids on Initialization
UpdateMargins(null, null);
}
}
//Calculate Grid Margin when an according Event is triggered
private void UpdateMargins(object sender, RoutedEventArgs e)
{
if(ParentWrappanel != null)
{
Point delta = m_expander.TranslatePoint(new Point(0d, 0d), ParentWrappanel);
//Create negative Margin to allow the Grid to be rendered outside of the Boundaries (full column under the Image)
this.Margin = new Thickness(-delta.X, 0, delta.X + m_expander.ActualWidth - ParentWrappanel.ActualWidth, 0);
//Theese Values arent calculated exavtly, just broad for example purpose
}
}
}
This is a little bit tricky to incorporate in existing Code. A working Example may help and is found HERE.
SideNote: If i got more time i would pack this stuff into a bigger Custom Control to use it like a normal UIElement (eg. Border). This would improve the re-usability and usability quite a lot.
EDIT
The 'newest' element in the ListView is also atop of the Z-Index, therefore it is 'above' the expanded StretchGrid and some Controls can not be clicked because they are 'behind' the next ListviewItem.
To fix this, add
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="1" />
</Trigger>
</Style.Triggers>
to the ListViewItem Style. Now when its visible it will place itself atop the other Controls.

This is what I have done so far:-
Images listed:
An Image Clicked - will show the Details view below it:
At the moment I am not closing other Detail Views - so below can happen for me.
However, all this needs is to propagate an event that some other item has been clicked. and close all other Detail Views (its mvvm and driven by a bool property)
======================================================
I have a Base UserControl which will load Items in a Top Down manner:
<Grid>
<Grid>
<ScrollViewer>
<ItemsControl ItemsSource="{Binding GridData, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
</Grid>
</Grid>
Each Row (Item) of this UserControl itself uses another ItemsControl. So that Images are lined up horizontally. Also, Each Item has a Details View Section (Border with Visibility controlled by Image clicks)
<UserControl.Resources>
<ResourceDictionary>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ItemsControl Grid.Row="0" ItemsSource="{Binding ImagesList, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Margin="5" Command="{Binding DataContext.ItemClickedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
CommandParameter="{Binding}">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Grid.Row="0" Source="{Binding Image, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Name="DisplayText" Grid.Row="1" HorizontalAlignment="Center" Text="{Binding DisplayText, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Border Margin="2" Grid.Row="1" Background="Black" Padding="10"
Visibility="{Binding ShowDetailsPanel, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BooleanToVisibilityConverter}}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Background="White" CornerRadius="10">
<Image Margin="5" Source="{Binding SelectedImage.Image, UpdateSourceTrigger=PropertyChanged}"/>
</Border>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Margin="20 20 0 0" FontSize="15"
Text="{Binding SelectedImage.ImageName, StringFormat={}Filename: {0}}" Foreground="White"/>
<TextBlock Grid.Row="1" Margin="20 20 0 0" FontSize="15"
Text="{Binding SelectedImage.Size, StringFormat={}Size: {0} bytes}" Foreground="White"/>
<TextBlock Grid.Row="2" Margin="20 20 0 0" FontSize="15"
Text="{Binding SelectedImage.Location, StringFormat={}Path: {0}}" Foreground="White"/>
<TextBlock Grid.Row="3" Margin="20 20 0 0" FontSize="15"
Text="{Binding SelectedImage.CreatedTime, StringFormat={}Last Modified: {0}}" Foreground="White"/>
</Grid>
</Grid>
</Border>
</Grid>
</Grid>

Related

DatePicker template, borders appear on mouse over

I have a weird problem,
My DatePicker shows in the middle some borders. I don't know where it comes from.
I changed every property of the DatePickerTextBox but it doesn't change anything.
Here is the XAML :
<Window.Resources>
<Style TargetType="{x:Type DatePicker}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DatePicker}">
<Border x:Name="MainBorder" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" CornerRadius="5">
<Grid x:Name="PART_Root" Margin="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<DatePickerTextBox x:Name="PART_TextBox"
BorderThickness="0"
BorderBrush="Transparent"
HorizontalContentAlignment="Stretch"
Padding="{TemplateBinding Padding}"
VerticalContentAlignment="Center"
Visibility="Visible"
SelectionBrush="#FF6F5DF5"
FocusVisualStyle="{x:Null}"
Grid.Column="0" Margin="0,3,0,0">
<DatePickerTextBox.Style>
<Style>
<Setter Property="TextBox.BorderThickness" Value="0"/>
</Style>
</DatePickerTextBox.Style>
</DatePickerTextBox>
<Button x:Name="PART_Button" HorizontalAlignment="Right" Margin="0,0,0.333,0.333" Width="24">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Image Source="Resources/Images/down.png"></Image>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
<Popup x:Name="PART_Popup" StaysOpen="False" AllowsTransparency="True" Margin="0,0,0.333,0.333" />
<Label x:Name="lblLabel" Content="{TemplateBinding Uid}" HorizontalContentAlignment="Center" Foreground="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" BorderThickness="0" Padding="12,0" FontFamily="Poppins" VerticalContentAlignment="Stretch" Margin="6,-11,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsDropDownOpen" Value="True">
<Setter TargetName="MainBorder" Property="BorderBrush" Value="#FF6F5DF5"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="MainBorder" Property="BorderBrush" Value="#FF6F5DF5"/>
<Setter TargetName="PART_TextBox" Property="BorderThickness" Value="0"/>
<Setter Property = "BorderBrush" Value="{Binding ToYourBorder}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<DatePicker Margin="10,260,0,0" VerticalAlignment="Top" Uid="Date de naissance *" FontSize="12" Height="40" BorderThickness="0" HorizontalAlignment="Left" Width="181" FontFamily="Poppins" Background="#FFFEFEFE" BorderBrush="#FF9A9A9A" Foreground="#FF727272" />
And here how it seems :
And on hover, there is another thin border inside :
Any idea, please?
DatePickerTextBox has it's own Template where the border and the triggers for the border are defined/hardcoded.
You need to take care of those in the template of DatePickerTextBox.
Change:
<DatePickerTextBox.Style>
<Style>
<Setter Property="TextBox.BorderThickness" Value="0"/>
</Style>
</DatePickerTextBox.Style>
To:
<DatePickerTextBox.Style>
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox" BorderThickness="0"
Text="{Binding Path=SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DatePickerTextBox.Style>
And it should work.
For a complete Template see DOCS

In Xaml, how can I bind the Thumb of a slider to one of the multiple ControlTemplate?

I am trying to create a Editable slider in WPF, where I need to bind the ControlTemplate with the Template of a Slider thumb which is not working.
I have 2 ControlTemplates and a slider. The Thumb of the slider should be displayed based on the selection of the Control template.
<ControlTemplate x:Uid="ControlTemplate_3" x:Key="StaticThumbTemplate" TargetType="{x:Type Thumb}">
<Border x:Uid="Border_3" Margin="1" BorderBrush="Gray" BorderThickness="1" Background="#EEEEEE" MinWidth="30" MaxWidth="50">
<TextBlock x:Uid="TextBlock_3" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2,0,2,0"
Text="{Binding Value, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:Slider}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
</Border>
</ControlTemplate>
<ControlTemplate x:Uid="ControlTemplate_4" x:Key="EditThumbTemplate" TargetType="{x:Type Thumb}">
<TextBox x:Uid="PART_Edit" Padding="2,0,2,0" x:Name="PART_Edit" MinWidth="30" VerticalAlignment="Center" LostFocus="PART_Edit_LostFocus"
Text="{Binding Value, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:Slider}, Mode=TwoWay}" />
</ControlTemplate>
<Style x:Uid="Style_3" x:Key="ThumbStyle" TargetType="{x:Type Thumb}">
<Setter x:Uid="Setter_3" Property="Template" Value="{StaticResource StaticThumbTemplate}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsTyping, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:Slider}}" Value="True">
<Setter x:Uid="Setter_4" Property="Template" Value="{StaticResource EditThumbTemplate}"/>
</DataTrigger>
</Style.Triggers>
</Style>
If the Property IsTyping gets changed from true/false, then corresponding ControlTemplate should be displayed. Currently only Static Thumb Template ControlTemplate is getting listed all the time.
[Update 1]
Complete code of Slider.xaml:
<Slider x:Class="SliderTest.Slider"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:SliderTest"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Slider.Resources>
<!-- TODO: Focus highlight! -->
<Style x:Uid="Style_1" x:Key="SliderLeftStyle" TargetType="{x:Type RepeatButton}">
<Setter x:Uid="Setter_1" Property="Template">
<Setter.Value>
<ControlTemplate x:Uid="ControlTemplate_1" TargetType="{x:Type RepeatButton}">
<Border x:Uid="Border_1" Background="Transparent">
<TextBlock x:Uid="TextBlock_1" Margin="2" HorizontalAlignment="Left" VerticalAlignment="Center" Text="{Binding MinStr, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Slider}}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Uid="Style_2" x:Key="SliderRightStyle" TargetType="{x:Type RepeatButton}">
<Setter x:Uid="Setter_2" Property="Template">
<Setter.Value>
<ControlTemplate x:Uid="ControlTemplate_2" TargetType="{x:Type RepeatButton}">
<Border x:Uid="Border_2" Background="Transparent">
<TextBlock x:Uid="TextBlock_2" Margin="2" HorizontalAlignment="Right" VerticalAlignment="Center" Text="{Binding MaxStr, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Slider}}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ControlTemplate x:Uid="ControlTemplate_3" x:Key="StaticThumbTemplate" TargetType="{x:Type Thumb}">
<Border x:Uid="Border_3" Margin="1" BorderBrush="Gray" BorderThickness="1" Background="#EEEEEE" MinWidth="30" MaxWidth="50">
<TextBlock x:Uid="TextBlock_3" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2,0,2,0"
Text="{Binding Value, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:Slider}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
/>
</Border>
</ControlTemplate>
<ControlTemplate x:Uid="ControlTemplate_4" x:Key="EditThumbTemplate" TargetType="{x:Type Thumb}">
<TextBox x:Uid="PART_Edit" Padding="2,0,2,0" x:Name="PART_Edit" MinWidth="30" VerticalAlignment="Center" LostFocus="PART_Edit_LostFocus"
Text="{Binding Value, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:Slider}, Mode=TwoWay}" />
</ControlTemplate>
<Style x:Uid="Style_3" x:Key="ThumbStyle" TargetType="{x:Type Thumb}">
<Setter x:Uid="Setter_3" Property="Template" Value="{StaticResource StaticThumbTemplate}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsTyping, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:Slider}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Value="True">
<Setter x:Uid="Setter_4" Property="Template" Value="{StaticResource EditThumbTemplate}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Slider.Resources>
<Slider.Template>
<ControlTemplate x:Uid="ControlTemplate_5">
<Grid x:Uid="Grid_1">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Uid="ColumnDefinition_1" Width="*"/>
<ColumnDefinition x:Uid="ColumnDefinition_2" Width="Auto"/>
<ColumnDefinition x:Uid="ColumnDefinition_3" Width="Auto"/>
</Grid.ColumnDefinitions>
<Border x:Uid="Border_4" Grid.Column="0" BorderBrush="Gray" BorderThickness="1">
<DockPanel x:Uid="PART_Outer" x:Name="PART_Outer" >
<Border x:Uid="Border_5" DockPanel.Dock="Left" Background="LightGray" Width="{Binding PadLeft, RelativeSource={RelativeSource Mode=TemplatedParent}}" Focusable="True"></Border>
<Border x:Uid="Border_6" DockPanel.Dock="Right" Background="LightGray" Width="{Binding PadRight, RelativeSource={RelativeSource Mode=TemplatedParent}}" Focusable="False"></Border>
<Track x:Uid="PART_Track" x:Name="PART_Track">
<Track.DecreaseRepeatButton>
<RepeatButton x:Uid="RepeatButton_1" Style="{StaticResource SliderLeftStyle}" Command="Slider.DecreaseLarge"/>
</Track.DecreaseRepeatButton>
<Track.Thumb>
<Thumb x:Uid="PART_Thumb" x:Name="PART_Thumb" Style="{StaticResource ThumbStyle}" MouseDoubleClick="PART_Thumb_OnMouseDoubleClick"/>
</Track.Thumb>
<Track.IncreaseRepeatButton>
<RepeatButton x:Uid="RepeatButton_2" Style="{StaticResource SliderRightStyle}" Command="Slider.IncreaseLarge" />
</Track.IncreaseRepeatButton>
</Track>
</DockPanel>
</Border>
<RepeatButton x:Uid="RepeatButton_3" Grid.Column="1" Padding="4,0,4,0" Command="Slider.DecreaseSmall"><</RepeatButton>
<RepeatButton x:Uid="RepeatButton_4" Grid.Column="2" Padding="4,0,4,0" Command="Slider.IncreaseSmall">></RepeatButton>
</Grid>
</ControlTemplate>
</Slider.Template>
Slider.xaml.cs:
public partial class Slider
{
private bool _isTyping;
public Slider()
{
InitializeComponent();
}
public bool IsTyping
{
get
{
return _isTyping;
}
set
{
_isTyping = value;
}
}
private double _valStr;
public double ValueStr
{
get { return _valStr; }
set { _valStr = value; }
}
private void PART_Thumb_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
IsTyping = true;
}
private void PART_Edit_LostFocus(object sender, RoutedEventArgs e)
{
IsTyping = false;
}
}
Where is the IsTyping property defined? If it is a property of the DataContext of the Slider control, you should add "DataContext." to the binding path:
<DataTrigger Binding="{Binding DataContext.IsTyping, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:Slider}}" Value="True">
If it is defined in the view model of the parent window, you should also change the AncestorType:
<DataTrigger Binding="{Binding DataContext.IsTyping,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" Value="True">
Also make sure that IsTyping is a dependency property, or that the class in which it is defined implements the INotifyPropertyChanged interface and that you raise the PropertyChanged event whenever the property is being set to a new value.

WPF List View Grouping Scroll Offset with Headers

I have an odd issue with a WPF listview:
Background
Using WPF ListView
Using Grid View to add columns
Virtualizing
Using 4 layers of groups to group the data into expanders in a hierarchical structure
Binding to CollectionViewSource defined in window.resources
Due to indentation of the data (the data is contained in expanders) the headers are offset from the column data so I use TranslateTransform to offset the headers by a small amount
Problem
Everything displays correctly and in the perfect hierarchical structure, however when I scroll to the right, there comes a point when the data keeps scrolling but the headers stop, which results in an offset between the headers and the data columns.
I am sure this has something to do with the way I am offsetting the headers, and the length of the headers compared to the data but I cant seem to find the reason for this problem.
List View Scrolled to just before the offset point
List View Scrolled to the end
Code
nb. I have omitted some style stuff as there is a limit on characters for answers here
<!-- The main grid -->
<ListView x:Name="DataGrid"
Margin="0"
Background="{StaticResource MainBackgroundBrush}"
BorderThickness="0"
Foreground="{StaticResource LightBackgroundBrush}"
ItemsSource="{Binding Source={StaticResource DataCollectionView}}"
ScrollViewer.IsDeferredScrollingEnabled="False"
SelectionMode="Single"
VirtualizingPanel.CacheLength="1,2"
VirtualizingStackPanel.IsContainerVirtualizable="True"
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.IsVirtualizingWhenGrouping="True"
VirtualizingStackPanel.ScrollUnit="Pixel"
VirtualizingStackPanel.VirtualizationMode="Recycling">
<!-- Some styles and resources exclusive to this list view -->
<ListView.Resources>
<Setter Property="IsExpanded" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Expander}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
SnapsToDevicePixels="true">
<DockPanel>
<ToggleButton x:Name="HeaderSite"
Width="600"
MinWidth="0"
MinHeight="0"
Margin="1"
Padding="{TemplateBinding Padding}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Background="{TemplateBinding Background}"
Content="{TemplateBinding Header}"
ContentTemplateSelector="{TemplateBinding HeaderTemplateSelector}"
DockPanel.Dock="Top"
FontFamily="{TemplateBinding FontFamily}"
FontSize="{TemplateBinding FontSize}"
FontStretch="{TemplateBinding FontStretch}"
FontStyle="{TemplateBinding FontStyle}"
FontWeight="{TemplateBinding FontWeight}"
Foreground="{TemplateBinding Foreground}"
IsChecked="{Binding IsExpanded, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Template="{StaticResource AnimatedExpanderButton}" />
<ContentPresenter x:Name="ExpandSite"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
DockPanel.Dock="Bottom"
Focusable="false"
Visibility="Collapsed" />
</DockPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsExpanded" Value="true">
<Setter TargetName="ExpandSite" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="ExpandDirection" Value="Up">
<Setter TargetName="HeaderSite" Property="Background" Value="Red" />
<Setter TargetName="ExpandSite" Property="DockPanel.Dock" Value="Top" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding Name}" Value="Title">
<Setter Property="IsEnabled" Value="False" />
<Setter Property="IsExpanded" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
<!-- Styles the column headers -->
<Style TargetType="{x:Type GridViewColumnHeader}">
<!-- Add the event handler for a right click on the header -->
<EventSetter Event="MouseRightButtonUp" Handler="GridViewColumnHeader_MouseRightButtonUp" />
<Setter Property="Background" Value="{StaticResource GradientBrush}" />
<Setter Property="ClickMode" Value="Press" />
<Setter Property="FontSize" Value="12" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="{StaticResource LightBackgroundBrush}" />
<Setter Property="Height" Value="30" />
<Setter Property="MinWidth" Value="20" />
<!-- Offset the column headers to match the column data as the expanders will have offset the data -->
<Setter Property="RenderTransform">
<Setter.Value>
<TranslateTransform X="13" />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
<Border BorderBrush="Black" BorderThickness="1,0,0,1">
<Grid Background="{TemplateBinding Background}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- The two column re sizers -->
<Thumb x:Name="PART_HeaderGripper"
Width="18"
Margin="0,0,-10,0"
HorizontalAlignment="Right"
Background="Black"
Cursor="SizeWE">
<Thumb.Template>
<ControlTemplate TargetType="{x:Type Thumb}">
<Border Padding="{TemplateBinding Padding}" Background="Transparent">
<Rectangle Width="1"
HorizontalAlignment="Center"
Fill="{TemplateBinding Background}" />
</Border>
</ControlTemplate>
</Thumb.Template>
</Thumb>
<!-- The main content of the header -->
<ContentPresenter Name="HeaderContent"
Grid.Column="0"
Margin="5"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.Resources>
<!-- Templates each level -->
<ListView.GroupStyle>
<!-- Style for groups at the top level. this level is equivalent to a single database -->
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Border Margin="1"
Background="{StaticResource FandFBrush}"
BorderBrush="Black"
BorderThickness="2"
CornerRadius="3">
<Expander Margin="0"
FontSize="12"
FontWeight="Bold"
Foreground="{StaticResource LightBackgroundBrush}"
Header="{Binding Name}"
IsExpanded="True">
<ItemsPresenter x:Name="IP"
Margin="0"
VirtualizingPanel.IsContainerVirtualizable="True"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
VirtualizingPanel.ScrollUnit="Item"
VirtualizingPanel.VirtualizationMode="Recycling" />
</Expander>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
<!-- Style for groups at the second level. this level is equivalent to a single case -->
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Border Margin="0"
Background="{StaticResource MainBackgroundBrush}"
BorderBrush="Black"
BorderThickness="2"
CornerRadius="3">
<Expander Margin="0"
FontSize="12"
FontWeight="Bold"
Foreground="{StaticResource LightBackgroundBrush}"
Header="{Binding Name}"
IsExpanded="True">
<ItemsPresenter x:Name="IP"
Margin="0"
VirtualizingPanel.IsContainerVirtualizable="True"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
VirtualizingPanel.ScrollUnit="Item"
VirtualizingPanel.VirtualizationMode="Recycling" />
</Expander>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
<!-- Style for groups at the third level. this level is equivalent to a single sample type -->
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Border Margin="1"
BorderBrush="Black"
BorderThickness="0"
CornerRadius="3">
<ItemsPresenter x:Name="IP"
Margin="0"
VirtualizingPanel.IsContainerVirtualizable="True"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
VirtualizingPanel.ScrollUnit="Item"
VirtualizingPanel.VirtualizationMode="Recycling" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
<!-- Style for groups at the fourth level. this level is equivalent to a single sample -->
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Border Margin="0,0,0,1"
Background="Transparent"
BorderBrush="Black"
BorderThickness="2,2,2,2"
CornerRadius="3,3,0,0"
Visibility="{Binding Items[0].Fragment.Sample.IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}">
<Expander Margin="0"
FontSize="12"
FontWeight="Bold"
Foreground="Black"
IsExpanded="True">
<Border Grid.Row="0"
Margin="1,0,1,1"
Background="{StaticResource MainBackgroundBrush}"
BorderBrush="Black"
BorderThickness="2,1,2,2"
CornerRadius="2">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- The measurements themselves -->
<Border Grid.Row="0"
Margin="0"
Background="{StaticResource MainBackgroundBrush}"
BorderBrush="Black"
BorderThickness="0,0,0,1"
CornerRadius="0">
<ItemsPresenter x:Name="IP"
Margin="0"
VirtualizingPanel.IsContainerVirtualizable="True"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
VirtualizingPanel.ScrollUnit="Item"
VirtualizingPanel.VirtualizationMode="Recycling" />
</Border> </Grid>
</Border>
</Expander>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
</ListView>

WPF Items control doesnot show VerticalScrollBar automatically

Here is the intention,
When items get added to ItemsControl and if the content is more than the available size I wish to see scrolling in ItemsControl. I bet this is the default behavior for any ItemsControl type.
So I generated a sample replicates my intention. Suggest me what I need to fix
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type ItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ItemsControl}">
<Border SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
<ScrollViewer VerticalScrollBarVisibility="Visible">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</StackPanel.Resources>
<ToggleButton Name="SomeToggle" Content="Show/Hide"/>
<Button Content="Add Item" Click="ButtonBase_OnClick" />
<TextBlock Text="Hide/Show on toggle" >
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsChecked,ElementName=SomeToggle}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<ItemsControl Name="ItemsCollection" >
</ItemsControl>
</StackPanel>
and Code behind:
private int counter = 0;
private ObservableCollection<string> coll;
public MainWindow()
{
coll= new ObservableCollection<string>();
//ItemsCollection.ItemsSource = coll;
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
ItemsCollection.Items.Add(string.Format("Item {0}", ++counter));
}
This is basically occurs each time you put a ScrollViewer inside a Stackpanel, and this is due to the way the Stackpanel works, take a look here
you could either put the Stackpanel inside a ScrollView, or better change your main panel to a Grid
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.Resources>
<Style TargetType="{x:Type ItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ItemsControl}">
<Border SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
<ScrollViewer VerticalScrollBarVisibility="Visible">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<ToggleButton Name="SomeToggle" Content="Show/Hide" Grid.Row="0"/>
<Button Content="Add Item" Click="ButtonBase_OnClick" Grid.Row="1"/>
<TextBlock Text="Hide/Show on toggle" Grid.Row="2">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsChecked,ElementName=SomeToggle}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<ItemsControl Name="ItemsCollection" Grid.Row="3">
</ItemsControl>
</Grid>
The only reason you are not able to see the scrollbars cause you have not set the height of your ItemsControl.
Every time you add a item it's height will expand and StackPanel will expand with it to contain the content. You have already defined ScrollViewer to your ItemsControl template you have to also decide at what point it has to work.
<ItemsControl Name="ItemsCollection" Height="200" >
</ItemsControl>
Then it will also not matter either you containing it in a StackPanel or any other control.
initial scroll bar
After adding items
with code
And just from understanding point of view. this will also work:
Remove style for item control & set the height of scroll viewer.
To handle the height of all elements:
<ScrollViewer MaxHeight="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}},Path=ActualHeight,Mode=OneWay}">
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type ItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ItemsControl}">
<Border SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
<ScrollViewer VerticalScrollBarVisibility="Visible">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</StackPanel.Resources>
<ToggleButton Name="SomeToggle" Content="Show/Hide"/>
<Button Content="Add Item" Click="Button_Click" />
<TextBlock Text="Hide/Show on toggle" >
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsChecked,ElementName=SomeToggle}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<ItemsControl Name="ItemsCollection" ItemsSource="{Binding list}"
MaxHeight="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}},Path=ActualHeight,Mode=OneWay}">
</ItemsControl>
</StackPanel>
</ScrollViewer>

WPF Datagrid binding custom column headers

I am trying to figure out how to bind a WPF DataGrid's column header and main data to a data source using an MVVM pattern. The result I'm looking for would look like this:
(source: vallelunga.com)
I've successfully styled the headers here, but I'm unsure how to bind the values in the headers. Specifically, the IsChecked property of the check-box, the selected index of the combo box and the value of the text box.
I was previously using a simple DataTable to populate the main grid data, but I'm going to need something more complex to hold both the grid data and the values for each column. Or perhaps I can store them as separate entities entirely.
So, does anyone have any idea of how I might pull off this binding? One limitation is that the columns must be auto-generated since I have no idea what they will be until runtime. The application simply loads the data form an Excel spreadsheet and there may be any number of columns present.
Thanks,
Brian
Here's what I ended up doing to use this with the MVVM pattern:
I have two sets of data for binding on my view model: one for the actual grid data and one for the column headers. Currently these are exposed as two properties:
// INotifyPropertyChanged support not shown for brevity
public DataTable GridData { get; set; }
public BindingList<ImportColumnInfo> ColumnData { get; set; }
The trick to working with two differing sets of data is in the grid. I have subclassed the DataGrid and given the grid an additional data source called ColumnSource, as a dependency property. This is what is bound to the ColumnData on my view model. I then set the header of each auto-generated column to the appropriately indexed data in the ColumnSource data source. The code is as follows:
public class ImporterDataGrid : DataGrid
{
protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
{
base.OnAutoGeneratingColumn(e);
int columnIndex = this.Columns.Count;
var column = new ImporterDataGridColumn();
column.Header = ColumnSource[columnIndex];
column.Binding = new Binding(e.PropertyName) { Mode = BindingMode.OneWay };
e.Column = column;
}
public IList ColumnSource
{
get { return (IList)GetValue(ColumnSourceProperty); }
set { SetValue(ColumnSourceProperty, value); }
}
public static readonly DependencyProperty ColumnSourceProperty = DependencyProperty.Register("ColumnSource", typeof(IList), typeof(ImporterDataGrid), new FrameworkPropertyMetadata(null));
}
I can now perform normal data binding in the templated header of my columns, which will all bind against the data in the ColumnData property of my view model.
UPDATE: I was asked to show the XAML for my grid. It's really basic, but here it is:
<Controls:ImporterDataGrid
AutoGenerateColumns="True" x:Name="previewDataGrid"
VerticalScrollBarVisibility="Visible"
HorizontalScrollBarVisibility="Visible"
IsReadOnly="True"
SelectionMode="Extended"
HeadersVisibility="Column"
ItemsSource="{Binding PreviewData}"
ColumnSource="{Binding PreviewColumnData}"
Style="{StaticResource ImporterDataGridStyle}"
Background="White" CanUserReorderColumns="False" CanUserResizeRows="False"
CanUserSortColumns="False" AlternatingRowBackground="#FFFAFAFA" AllowDrop="True" />
And here is the ImporterColumnHeaderStyle:
<Style x:Key="ImporterDataGridColumnHeaderStyle" TargetType="{x:Type toolkit:DataGridColumnHeader}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type toolkit:DataGridColumnHeader}">
<Grid>
<toolkit:DataGridHeaderBorder Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" IsClickable="{TemplateBinding CanUserSort}" IsHovered="False" IsPressed="False" SortDirection="{TemplateBinding SortDirection}">
<Grid>
<CheckBox Height="16" Margin="6,6,16,0" Name="importCheckBox" IsChecked="{Binding Path=Import}" VerticalAlignment="Top">Import Column</CheckBox>
<StackPanel IsEnabled="{Binding Path=Import}">
<ComboBox Height="24" Margin="6,29,6,0" Name="columnTypeComboBox" VerticalAlignment="Top" SelectedValue="{Binding ColumnType}" ItemsSource="{Binding Source={local:EnumList {x:Type Models:ImportColumnType}}}">
</ComboBox>
<TextBox Height="23" Margin="6,6,6,33" Name="customHeadingTextBox" VerticalAlignment="Bottom" Text="{Binding Path=CustomColumnName}" IsEnabled="{Binding ColumnType, Converter={StaticResource ColumnTypeToBooleanConverter}}" />
</StackPanel>
<TextBlock Height="20" Margin="6,0,6,7" Name="originalHeadingTextBlock" Text="{Binding Path=OriginalColumnName}" VerticalAlignment="Bottom" Foreground="Gray" />
</Grid>
</toolkit:DataGridHeaderBorder>
<Thumb x:Name="PART_LeftHeaderGripper" HorizontalAlignment="Left">
<Thumb.Style>
<Style TargetType="{x:Type Thumb}">
<Setter Property="Width" Value="8"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Cursor" Value="SizeWE"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Thumb.Style>
</Thumb>
<Thumb x:Name="PART_RightHeaderGripper" HorizontalAlignment="Right">
<Thumb.Style>
<Style TargetType="{x:Type Thumb}">
<Setter Property="Width" Value="8"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Cursor" Value="SizeWE"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Thumb.Style>
</Thumb>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I am definitely a WPF / MVVM / databinding noob, but have been working hard on this stuff lately. I don't know what you have wired up so far, but first you'll want to set the DataContext for your View. Since you're using MVVM, I assume you have a ViewModel, so that should be the DataContext for your View.
i.e. if you have your View create / own your ViewModel, it could look something like this:
MyViewModel vm = new MyViewModel();
this.DataContext = vm;
You can easily databind your CheckBox, ComboBox, and TextBox to properties in your ViewModel. I have found the easiest way is to make your ViewModel inherit from a base viewmodel class, like the one that Josh Smith wrote. This will give you a method to call internally when you want the ViewModel to notify the GUI of any changes in values.
Assuming you have properties like ImportColumn, LastName, and LastNameText (all C# properties, not fields that call OnPropertyChanged accordingly), then your XAML would look something like this:
<CheckBox IsChecked="{Binding ImportColumn}" />
<ComboBox SelectedItem="{Binding LastName}" />
<TextBox Text="{Binding LastName Text, Mode=TwoWay}" />
I hope this helps you out. If not, please comment and I'll try to do as best as I can to try other things out.
We do something similar in our app.
What i have done is derived my own column type (DataGridSearchableBooleanColumn), then i replace the DataGridColumnHeader template, i put two content presenters in there. the first i bind to the content (the same as the default template) the second i bind to the column. I use a data template for the column (i have a few of them for different search types (text, combo, boolean). then i add the extra properties to the column so i can bind to them. See if this code makes sense.
<!--Style for the datagrid column headers, contains a text box for searching-->
<Style
x:Key="columnHeaderStyle"
TargetType="dg:DataGridColumnHeader">
<Setter
Property="Foreground"
Value="#FF000000" />
<Setter
Property="HorizontalContentAlignment"
Value="Left" />
<Setter
Property="VerticalContentAlignment"
Value="Center" />
<Setter
Property="IsTabStop"
Value="False" />
<Setter
Property="Padding"
Value="1,2,1,2" />
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate
TargetType="dg:DataGridColumnHeader">
<Grid
x:Name="Root">
<dg:DataGridHeaderBorder
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
IsClickable="{TemplateBinding CanUserSort}"
IsHovered="{TemplateBinding IsMouseOver}"
IsPressed="{TemplateBinding IsPressed}"
SeparatorBrush="{TemplateBinding SeparatorBrush}"
SeparatorVisibility="{TemplateBinding SeparatorVisibility}"
SortDirection="{TemplateBinding SortDirection}">
<Grid
HorizontalAlignment="Stretch"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
<Grid.Resources>
<DataTemplate
DataType="{x:Type local:DataGridSearchableBooleanColumn}">
<CheckBox
Margin="0,5,0,0"
IsThreeState="True"
IsChecked="{Binding Path=IsChecked}" />
</DataTemplate>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition
Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition
Height="19" />
<RowDefinition
Height="Auto" />
</Grid.RowDefinitions>
<ContentPresenter
Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay, Path=Content}" />
<Path
x:Name="SortIcon"
Fill="#FF444444"
Stretch="Uniform"
HorizontalAlignment="Left"
Margin="4,0,0,0"
VerticalAlignment="Center"
Width="8"
Opacity="0"
RenderTransformOrigin=".5,.5"
Grid.Column="1"
Data="F1 M -5.215,6.099L 5.215,6.099L 0,0L -5.215,6.099 Z ">
<Path.RenderTransform>
<ScaleTransform
ScaleX=".9"
ScaleY=".9" />
</Path.RenderTransform>
</Path>
<ContentPresenter
x:Name="columnHeaderContentPresenter"
Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Column}"
Grid.Row="1"
Grid.ColumnSpan="2"
Margin="0,0,0,0" />
</Grid>
</dg:DataGridHeaderBorder>
<Thumb
x:Name="PART_LeftHeaderGripper"
HorizontalAlignment="Left">
<Thumb.Style>
<Style
TargetType="{x:Type Thumb}">
<Setter
Property="Width"
Value="8" />
<Setter
Property="Background"
Value="Transparent" />
<Setter
Property="Cursor"
Value="SizeWE" />
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate
TargetType="{x:Type Thumb}">
<Border
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Thumb.Style>
</Thumb>
<Thumb
x:Name="PART_RightHeaderGripper"
HorizontalAlignment="Right">
<Thumb.Style>
<Style
TargetType="{x:Type Thumb}">
<Setter
Property="Width"
Value="8" />
<Setter
Property="Background"
Value="Transparent" />
<Setter
Property="Cursor"
Value="SizeWE" />
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate
TargetType="{x:Type Thumb}">
<Border
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Thumb.Style>
</Thumb>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

Resources