Wednesday, 16 November 2011

WPF TextBlock Control

How to change the line height within a TextBlock

To change the line hight within a TextBlock, you have to set the LineHeight to the desired height (in logical units) and also the LineStackingStrategy to BlockLineHeight, because otherwhise you will not see any effect.
 
<TextBlock Text="This is a 
multiline text." 
           LineHeight="25" LineStackingStrategy="BlockLineHeight" />

WPF ListView Control

How to Hide the Header of a ListView

To hide the header of a ListView you can modify the Visibility property of the ColumnHeaderContainer by overriding the style locally.
<ListView>
    <ListView.View>
        <GridView>
            <GridView.ColumnHeaderContainerStyle>
               <Style>
                   <Setter Property="FrameworkElement.Visibility" Value="Collapsed"/>
               </Style>
            </GridView.ColumnHeaderContainerStyle>
            <GridView.Columns>
                ...
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>
 

WPF ListBox Control

Introduction

The ListBox control displays a list of items. The user can select one or multiple items depending on the selection mode. The typical usage of a listbox in WPF is to bind its items to a list of business objects and display them by applying a data template.

 
<ListBox Margin="20">
    <ListBoxItem>New York</ListBoxItem>
    <ListBoxItem>Los Angeles</ListBoxItem>
    <ListBoxItem>Paris</ListBoxItem>
    <ListBoxItem>Zürich</ListBoxItem>
</ListBox>
 
 

How to define a Trigger for IsSelected in the DataTemplate

If you want to change the appearance of a ListBoxItem when it is selected, you have to bind the IsSelected property of the ListBoxItem. But this is a bit tricky, you have to use a relative source with FindAcestor to navigate up the visual tree until you reach the ListBoxItem.
 
<DataTemplate x:Key="myDataTemplate">
    <Border x:Name="border" Height="50">
        <TextBlock Text="{Binding Text}" />
    </Border>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding RelativeSource=
            {RelativeSource Mode=FindAncestor, AncestorType=
                {x:Type ListBoxItem}},Path=IsSelected}" Value="True">
            <Setter TargetName="border" Property="Height" Value="100"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>
 
 

More articles about the ListBox

Apply a DataTemplate
Strech an Item
Selected Item Background
Layout of Items


Radio Button

Introduction

The RadioButton control has its name from old analog radios which had a number of programmable station buttons. When you pushed one in, the previosly selected poped out. So only one station can be selected at a time.
The RadioButton control has the same behavior. It lets the user choose one option out of a few. It the list of options gets longer, you should prefer a combo or list box instead.
To define which RadioButtons belong togehter, you have to set the GroupName to the same name.
To preselect one option set the IsChecked property to True.

 
<StackPanel>
    <RadioButton GroupName="Os" Content="Windows XP" IsChecked="True"/>
    <RadioButton GroupName="Os" Content="Windows Vista" />
    <RadioButton GroupName="Os" Content="Windows 7" />
    <RadioButton GroupName="Office" Content="Microsoft Office 2007" IsChecked="True"/>
    <RadioButton GroupName="Office" Content="Microsoft Office 2003"/>
    <RadioButton GroupName="Office" Content="Open Office"/>
</StackPanel>
 
 

How to DataBind Radio Buttons in WPF

The radio button control has a known issue with data binding. If you bind the IsChecked property to a boolean and check the RadioButton, the value gets True. But when you check another RadioButton, the databound value still remains true.
The reason for this is, that the Binding gets lost during the unchecking, because the controls internally calls ClearValue() on the dependency property.
 
<Window.Resources>
   <EnumMatchToBooleanConverter x:Key="enumConverter" />
</Window.Resources>
 
 
<RadioButton Content="Option 1" GroupName="Options1" 
             IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, 
                                 Converter={StaticResource enumConverter},
                                 ConverterParameter=Option1}"  />
<RadioButton Content="Option 2" GroupName="Options2" 
             IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, 
                                 Converter={StaticResource enumConverter},
                                 ConverterParameter=Option2}"  />
<RadioButton Content="Option 3" GroupName="Options3" 
             IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, 
                                 Converter={StaticResource enumConverter},
                                 ConverterParameter=Option3}"  />
 
 
 
public class EnumMatchToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, 
                              object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return false;
 
            string checkValue = value.ToString();
            string targetValue = parameter.ToString();
            return checkValue.Equals(targetValue, 
                     StringComparison.InvariantCultureIgnoreCase);
        }
 
        public object ConvertBack(object value, Type targetType, 
                                  object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return null;
 
            bool useValue = (bool)value;
            string targetValue = parameter.ToString();
            if (useValue)
                return Enum.Parse(targetType, targetValue);
 
            return null;
        }
    }   
 
 

WPF Slider Control

How to Make a Slider Snap to Integer Values

If you just set the Minimum and Maximum of a slider and choose a value the result is determined by the pixel position of the thumb. The value is typically a high-precision value with many decimal places. To allow only integer values you have to set the IsSnapToTickEnabled property to True.
<Slider Minimum="0"
        Maximum="20"
        IsSnapToTickEnabled="True"
        TickFrequency="2"
 

Popup Control

Introduction follows...

How to make the popup close, when it loses focus

Just set the StaysOpen property to False. Unfortunately this is not the default behavior
 
<Popup StaysOpen="False" />
 

Menus in WPF

Menu

The Menu control derives from HeaderedItemsControl. It stacks it items horizontally and draws the typical gray background. The only property that the Menu adds to ItemsControl is the IsMainMenu property. This controls if the menu grabs the focus if the user presses F10 or the ALT key.
 
<Menu IsMainMenu="True">
    <MenuItem Header="_File" />
    <MenuItem Header="_Edit" />
    <MenuItem Header="_View" />
    <MenuItem Header="_Window" />
    <MenuItem Header="_Help" />
</Menu>
 
 

MenuItem

The MenuItem is a HeaderedItemsControl. The content of the Header property is the caption of the menu. The Items of a MenuItems are its sub menus. The Icon property renders a second content on the left of the caption. This is typically used to draw a little image. But it can be used for type of content.
You can define a keyboard shortcut by adding an underscore in front of a character.
 
<MenuItem Header="_Edit">
    <MenuItem Header="_Cut" Command="Cut">
        <MenuItem.Icon>
            <Image Source="Images/cut.png" />
        </MenuItem.Icon>
    </MenuItem>
    <MenuItem Header="_Copy" Command="Copy">
        <MenuItem.Icon>
            <Image Source="Images/copy.png" />
        </MenuItem.Icon>
    </MenuItem>
    <MenuItem Header="_Paste" Command="Paste">
        <MenuItem.Icon>
            <Image Source="Images/paste.png" />
        </MenuItem.Icon>
    </MenuItem>
</MenuItem>
 
 

Checkable MenuItems

You can make a menu item checkable by setting the IsCheckable property to true. The check state can be queried by the IsChecked property. To get notified when the check state changes you can add a handler to the Checked and Unchecked property.
 
<MenuItem Header="_Debug">
    <MenuItem Header="Enable Debugging" IsCheckable="True" />
</MenuItem>
 
 

Separators

Separator is a simple control to group menu items. It's rendered as a horizontal line. It can also be used in ToolBar and StatusBar.
 
<Menu>
    <MenuItem Header="_File">
        <MenuItem Header="_New..." />
        <Separator />
        <MenuItem Header="_Open..." />
        <Separator />
        <MenuItem Header="_Save" />
        <MenuItem Header="_Save As..." />
        <Separator />
        <MenuItem Header="_Exit" />
    </MenuItem>
</Menu>
 
 

Callbacks

You can register a callback to any menu item by adding a callback to the Click event.
 
<Menu>
    <MenuItem Header="_File">
        <MenuItem Header="_New..."  Click="New_Click"/>
    </MenuItem>
</Menu>
 
 
 
private void New_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("You clicked 'New...'");
}
 
 

How to bind MenuItems dynamically using MVVM

If you are using the model-view-viewmodel pattern, you probably want to define the available menu command dynamically in your code and then bind them to a MenuItem control. The following sample shows you how to do this:
 
<Menu>
    <Menu.Resources>
        <Style x:Key="ThemeMenuItemStyle" TargetType="MenuItem">
           <Setter Property="Header" Value="{Binding Name}"></Setter>
           <Setter Property="Command" Value="{Binding ActivateCommand}"/>
           <Setter Property="IsChecked" Value="{Binding IsActive}" />
           <Setter Property="IsCheckable" Value="True"/>
        </Style>
    </Menu.Resources>
    <MenuItem Header="Themes" ItemsSource="{Binding Themes}" 
              ItemContainerStyle="{StaticResource ThemeMenuItemStyle}"  />
</Menu>
 
 

Keyboard Shortcuts

To add a keyboard shortcut to a menu item, add a underscode "_" in front of the caracter you want to use as your hot key. This automatically sets the InputGestureText to an appropriate value. But you can also override the proposed text by setting this property to a text of your choice.

WPF Expander Control

Introduction

The Expander control is like a GroupBox but with the additional feature to collapse and expand its content. It derives from HeaderedContentControl so it has a Header property to set the header content, and a Content property for the expandable content.
It has a IsExpanded property to get and set if the expander is in expanded or collapsed state.
In collapsed state the expander takes only the space needed by the header. In expanded state it takes the size of header and content together.
 
<Expander Header="More Options">
    <StackPanel Margin="10,4,0,0">
        <CheckBox Margin="4" Content="Option 1" />
        <CheckBox Margin="4" Content="Option 2" />
        <CheckBox Margin="4" Content="Option 3" />
    </StackPanel>
</Expander>
 
 

Context Menus in WPF

Context Menus can be defined on any WPF controls by setting the ContextMenu property to an instance of a ContextMenu. The items of a context menu are normal MenuItems.
 
<RichTextBox>
    <RichTextBox.ContextMenu>
        <ContextMenu>
            <MenuItem Command="Cut">
                <MenuItem.Icon>
                    <Image Source="Images/cut.png" />
                </MenuItem.Icon>
            </MenuItem>
            <MenuItem Command="Copy">
                <MenuItem.Icon>
                    <Image Source="Images/copy.png" />
                </MenuItem.Icon>
            </MenuItem>
            <MenuItem Command="Paste">
                <MenuItem.Icon>
                    <Image Source="Images/paste.png" />
                </MenuItem.Icon>
            </MenuItem>
        </ContextMenu>
    </RichTextBox.ContextMenu>
</RichTextBox>
 
 

Show ContextMenus on a disabled controls

If you rightclick on a disabled control, no context menu is shown by default. To enable the context menu for disabled controls you can set the ShowOnDisabled attached property of the ContextMenuService to True.
 
<RichTextBox IsEnabled="False" ContextMenuService.ShowOnDisabled="True">
    <RichTextBox.ContextMenu>
        <ContextMenu>
            ...
        </ContextMenu>
    </RichTextBox.ContextMenu>
</RichTextBox>
 
 

Merge ContextMenus

If you want to fill a menu with items coming from multiple sources, you can use the CompositeCollection to merge multiple collection into one.
 
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib">
  <Grid Background="Transparent">
    <Grid.Resources>
        <x:Array Type="{x:Type sys:Object}" x:Key="extensions">
            <Separator />
            <MenuItem Header="Extension MenuItem 1" />
            <MenuItem Header="Extension MenuItem 2" />
            <MenuItem Header="Extension MenuItem 3" />
        </x:Array>
    </Grid.Resources>
    <Grid.ContextMenu>
        <ContextMenu>
            <ContextMenu.ItemsSource>
                <CompositeCollection>
                    <MenuItem Header="Standard MenuItem 1" />
                    <MenuItem Header="Standard MenuItem 2" />
                    <MenuItem Header="Standard MenuItem 3" />
                    <CollectionContainer Collection="{StaticResource extensions}" />
                </CompositeCollection>
            </ContextMenu.ItemsSource>
        </ContextMenu>
    </Grid.ContextMenu>
  </Grid>
</Window>
 
 

How to bind a Command on a ContextMenu within a DataTemplate using MVVM

Since the Popuup control has it's separate visual tree, you cannot use find ancestor to find the Grid. The trick here is to use the PlacementTarget property, that contains the element, the ContextMenu is aligned to, what is the Grid in our case.
But this is only half of the solution. Because of the data template, the DataContext is set to a dataitem, and not the view model. So you need another relative source lookup, to find the view model. Trick Nr. 2 is to use the Tag property to bind the view model from outside to the grid, which is the PlacementTarget used above. And there we are.
 
<DataTemplate>
   <Grid Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}">
      <Grid.ContextMenu>
          <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
             <MenuItem Content="Cut" Command="{Binding CutCommand}" />
             <MenuItem Content="Copy" Command="{Binding CopyCommand}" />
             <MenuItem Content="Paste" Command="{Binding PasteCommand}" />
          </ContextMenu>
      </Grid.ContextMenu>
   </Grid>
</DataTemplate>
 
 

How to open a context menu from code

The following sample shows you how to open a context menu of a control programmatically:
 
private void OpenContextMenu(FrameworkElement element)
{
    if( element.ContextMenu != null )
    {
       element.ContextMenu.PlacementTarget = element;
       element.ContextMenu.IsOpen = true;
    }
}

WPF TextBox

How to enable spell checking

TextBox and RichTextBox provide an out-of-the-box spell checking functionality. It is available for the following languages: English, Spanish, German and French. It can be enabled by setting the attached property SpellCheck.IsEnabled to true.
 
    <TextBox SpellCheck.IsEnabled="True" Language="en-US" />
 
 

How to validate input

By using a regular expression, you can easily limit and validate the input of the user. The following code snippet shows how to do it:
 
protected override void OnTextInput(TextCompositionEventArgs e)
{
    string fullText = Text.Remove(SelectionStart, SelectionLength) + e.Text;
    if (_regex != null && !_regex.IsMatch(fullText))
    {
        e.Handled = true;
    }
    else
    {
        base.OnTextInput(e);
    }
}
 
 

WPF DataGrid Control

Introduction

Since .NET 4.0, Microsoft is shipping a DataGrid control that provides all the basic functionality needed, like:

Basic usage: Auto generate columns

To show a basic data grid , just drop a DataGrid control to your view and bind the ItemsSource to a collection of data objects and you're done. The DataGrid provides a feature called AutoGenerateColumns that automatically generates column according to the public properties of your data objects. It generates the following types of columns:
  • TextBox columns for string values
  • CheckBox columns for boolean values
  • ComboBox columns for enumerable values
  • Hyperlink columns for Uri values
 
<DataGrid ItemsSource="{Binding Customers}" />
 
 

Manually define columns

Alternatively you can define your columns manually by setting the AutoGenerateColumns property to False. In this case you have to define the columns in the Columns collection of the data grid. You have the following types of columns available:
  • DataGridCheckBoxColumn for boolean values
  • DataGridComboBoxColumn for enumerable values
  • DataGridHyperlinkColumn for Uri values
  • DataGridTemplateColumn to show any types of data by defining your own cell template
  • DataGridTextColumn to show text values
 
<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="{Binding Image}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
 
 

Selection

The data grid includes a variety of selection modes. They are configured by the SelectionMode and SelectionUnit property.
  • The SelectionMode can be set to Single or Extended to define if one or multiple units can be selected simultaneously.
  • The SelectionUnit defines the scope of one selection unit. It can be set to Cell, CellAndRowHeader and FullRow.
 
<DataGrid ItemsSource="{Binding Customers}" 
          SelectionMode="Extended" SelectionUnit="Cell" />
 
 

Column sorting, reordering and resizing

The data grid provides features to sort, reorder and resize columns. They can be enabled or disabled by the following properties:
  • CanUserReorderColumns enables or disables column re-ordering
  • CanUserResizeColumns enables or disables column resizing
  • CanUserResizeRows enables or disables row resizing
  • CanUserSortColumns enables or disables column sorting
 
<DataGrid ItemsSource="{Binding Customers}" 
          CanUserReorderColumns="True" CanUserResizeColumns="True" 
          CanUserResizeRows="False" CanUserSortColumns="True"/>
 
 

Grouping

The data grid also supports grouping. To enable grouping you have to define a CollectionView that contains to least one GroupDescription that defines the criterias how to group.
 
Customers = new ListCollectionView(_customers);
Customers.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));
 
 
Second thing you need to do is defining a template how the groups should look like. You can do this by setting the GroupStyle to something like the following snippet.
 
<DataGrid ItemsSource="{Binding GroupedCustomers}">
    <DataGrid.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Name}" />
                    </StackPanel>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
            <GroupStyle.ContainerStyle>
                <Style TargetType="{x:Type GroupItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type GroupItem}">
                                <Expander>
                                    <Expander.Header>
                                        <StackPanel Orientation="Horizontal">
                                          <TextBlock Text="{Binding Path=Name}" />
                                          <TextBlock Text="{Binding Path=ItemCount}"/>
                                          <TextBlock Text="Items"/>
                                        </StackPanel>
                                    </Expander.Header>
                                    <ItemsPresenter />
                                </Expander>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </GroupStyle.ContainerStyle>
        </GroupStyle>
    </DataGrid.GroupStyle>
</DataGrid>
 
 

Row Details

The data grid provides a feature that shows a detail panel for a selected row. It can be enabled by setting a DataTemplate to the RowDetailsTemplate property. The data template gets the object that is bound to this row passed by the DataContext and can bind to it.
 
<DataGrid ItemsSource="{Binding Customers}">
    <DataGrid.Columns>
    <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
    </DataGrid.Columns>
    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <Image Height="100" Source="{Binding Image}" />
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
</DataGrid>
 
 

Row Details depending on the type of data

You can specify a RowDetailsTemplateSelector that selects a data template according to the type or data that this row contains. To do this, create a type that derives from DataTemplateSelector and override the SelectTemplate method. In the items argument you get the data and you can determine which data template to display. Return an instance of that data template as return value.
 
public class GenderTemplateSelector : DataTemplateSelector
{
    public DataTemplate MaleTemplate { get; set; }
    public DataTemplate FemaleTemplate { get; set; }
 
    public override DataTemplate SelectTemplate(object item, 
                  DependencyObject container)
    {
        var customer = item as Customer;
        if (customer == null)
            return base.SelectTemplate(item, container);
 
        if( customer.Gender == Gender.Male)
        {
            return MaleTemplate;
        }
        return FemaleTemplate;
    }
}
 
 

 
<l:GenderTemplateSelector x:Key="genderTemplateSelector">
    <l:GenderTemplateSelector.MaleTemplate>
        <DataTemplate>
            <Grid Background="LightBlue">
                <Image Source="{Binding Image}" Width="50" />
            </Grid>
        </DataTemplate>
    </l:GenderTemplateSelector.MaleTemplate>
    <l:GenderTemplateSelector.FemaleTemplate>
        <DataTemplate>
            <Grid Background="Salmon">
                <Image Source="{Binding Image}" Width="50" />
            </Grid>
        </DataTemplate>
    </l:GenderTemplateSelector.FemaleTemplate>
</l:GenderTemplateSelector>
 
<DataGrid ItemsSource="{Binding Customers}" 
          RowDetailsTemplateSelector="{StaticResource genderTemplateSelector}" />
 
 

Alternating BackgroundBrush

You can define a an AlternatingRowBackground that is applied every even row. You can additionally specify an AlternationCount if you only want to ink every every n-th data row.
 
<DataGrid ItemsSource="{Binding Customers}" 
          AlternatingRowBackground="Gainsboro"  AlternationCount="2"/>
 
 

Frozen Columns

The data grid also supports the feature to freeze columns. That means they stay visible while you scoll horizontally through all columns. This is a useful feature to keep a referencing column like an ID or a name always visible to keep your orientation while scrolling.
To freeze a numer of columns just set the FrozenColumnCount property to the number of columns you want to freeze.
 
<DataGrid ItemsSource="{Binding Customers}" FrozenColumnCount="2"  />
 
 

Headers visbility

You can control the visibility of row and column headers by setting the HeadersVisibility property to either None,Row,Column or All
 
<DataGrid ItemsSource="{Binding Customers}" HeadersVisibility="None" />
 
 

How to template autogenerated columns

If you want to autogenerate columns using AutoGenerateColumns="True", you cannot use CellTemplates, because the DataGrid autogenerates either a text, combo, hyperlink or checkbox column, but none of these are templateable. A simple workaround is to hook into the autogeneration, cancel it and always create a DataGridTemplateColumn. The following snippet shows the idea (the code is just a draft):
 
public class MyDataGrid : DataGrid
{
 
    public DataTemplateSelector CellTemplateSelector
    {
        get { return (DataTemplateSelector)GetValue(CellTemplateSelectorProperty); }
        set { SetValue(CellTemplateSelectorProperty, value); }
    }
 
    public static readonly DependencyProperty CellTemplateSelectorProperty =
        DependencyProperty.Register("Selector", typeof(DataTemplateSelector), typeof(MyDataGrid), 
        new FrameworkPropertyMetadata(null));
 
 
 
    protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
    {
        e.Cancel = true;
        Columns.Add(new DataGridTemplateColumn
            {
                Header = e.Column.Header, 
                CellTemplateSelector = CellTemplateSelector
            });
    }
}
 
 
 
<l:MyDataGrid ItemsSource="{Binding}" 
              AutoGenerateColumns="True" 
              CellTemplateSelector="{StaticResource templateSelector}" />

ToolTips in WPF


 
<Button Content="Submit">
    <Button.ToolTip>
        <ToolTip>
            <StackPanel>
                <TextBlock FontWeight="Bold">Submit Request</TextBlock>
                <TextBlock>Submits the request to the server.</TextBlock>
            </StackPanel>
        </ToolTip>
    </Button.ToolTip>
</Button>
 
 

How to show ToolTips on disabled controls

When you disable a control with IsEnabled=False the tooltip does not show anymore. If you want to have the tooltip appear anyway you have to set the attaached property ToolTipService.ShowOnDisabled to True.
 
<Button IsEnabled="False" 
        ToolTip="Saves the current document"
        ToolTipService.ShowOnDisabled="True"
        Content="Save">
</Button>
 
 

How to change the show duration of a ToolTip

The static class ToolTipService allows you to modify the show duration of the tooltip
 
<Button ToolTip="Saves the current document"
        ToolTipService.ShowDuration="20"
        Content="Save">
</Button>
 

ItemsControl

How to automatically scroll to the last item

 
<ListBox l:ItemsControlHelper.ScrollToLastItem="true" />
 
 


 
public static class ItemsControlHelper
{
    public static readonly DependencyProperty ScrollToLastItemProperty =
        DependencyProperty.RegisterAttached("ScrollToLastItem",
            typeof(bool), typeof(ItemsControlHelper),
            new FrameworkPropertyMetadata(false, OnScrollToLastItemChanged));
 
    public static void SetScrollToLastItem(UIElement sender, bool value)
    {
        sender.SetValue(ScrollToLastItemProperty, value);
    }
 
    public static bool GetScrollToLastItem(UIElement sender)
    {
        return (bool)sender.GetValue(ScrollToLastItemProperty);
    }
 
    private static void OnScrollToLastItemChanged(DependencyObject sender, 
                            DependencyPropertyChangedEventArgs e)
    {
        var itemsControl = sender as ItemsControl;
 
        if (itemsControl != null)
        {
            itemsControl.ItemContainerGenerator.StatusChanged += 
                     (s,a) => OnItemsChanged(itemsControl,s,a);
        }
    }
 
    static void OnItemsChanged(ItemsControl itemsControl, object sender, EventArgs e)
    {
        var generator = sender as ItemContainerGenerator;
        if( generator.Status == GeneratorStatus.ContainersGenerated )
        {
            if (itemsControl.Items.Count > 0)
            {
                ScrollIntoView(itemsControl, 
                 itemsControl.Items[itemsControl.Items.Count - 1]);
            }
        }
    }
 
    private static void ScrollIntoView(ItemsControl itemsControl, object item)
    {
        if (itemsControl.ItemContainerGenerator.Status == 
            GeneratorStatus.ContainersGenerated)
        {
            OnBringItemIntoView(itemsControl, item);
        }
        else
        {
            Func<object, object> onBringIntoView = 
                    (o) => OnBringItemIntoView(itemsControl, item);
            itemsControl.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, 
                  new DispatcherOperationCallback(onBringIntoView));
        } 
    }
 
    private static object OnBringItemIntoView(ItemsControl itemsControl, object item)
    {
        var element = itemsControl.ItemContainerGenerator.
                 ContainerFromItem(item) as FrameworkElement;
        if (element != null)
        {
            element.BringIntoView();
        }
        return null;
    }
}