tags:

views:

568

answers:

1

I want to create a style for a WPF listbox that includes a button in the control template that the user can click on and it clears the listbox selection. I dont want to use codebehind so that this style can be applied to any listbox. I have tried using event triggers and storyboards and it has proved problematic as it only works first time and stopping the storyboard sets the previous selection back. I know I could use a usercontrol but I want to know if it is possible to achieve this using onlu a style.

A: 

It is not possible to achieve this using XAML and only the classes provided by the .NET framework. However you can still produce a reusable solution by defining a new command (call it ClearSelectionCommand) and a new attached property (call it ClearSelectionOnCommand).

Then you can incorporate those elements into your style.

Example:

public class SelectorBehavior
{
    public static RoutedCommand 
        ClearSelectionCommand = 
            new RoutedCommand(
                "ClearSelectionCommand", 
                typeof(SelectorBehavior));

    public static bool GetClearSelectionOnCommand(DependencyObject obj)
    {
        return (bool)obj.GetValue(ClearSelectionOnCommandProperty);
    }

    public static void SetClearSelectionOnCommand(
        DependencyObject obj, 
        bool value)
    {
        obj.SetValue(ClearSelectionOnCommandProperty, value);
    }

    public static readonly DependencyProperty ClearSelectionOnCommandProperty =
        DependencyProperty.RegisterAttached(
            "ClearSelectionOnCommand", 
            typeof(bool), 
            typeof(SelectorBehavior), 
            new UIPropertyMetadata(false, OnClearSelectionOnCommandChanged));

    public static void OnClearSelectionOnCommandChanged(
        DependencyObject d, 
        DependencyPropertyChangedEventArgs e)
    {
        Selector selector = d as Selector;
        if (selector == null) return;
        bool nv = (bool)e.NewValue, ov = (bool)e.OldValue;
        if (nv == ov) return;

        if (nv)
        {
            selector.CommandBindings.Add(
                new CommandBinding(
                    ClearSelectionCommand, 
                    ClearSelectionCommand_Executed, 
                    ClearSelectionCommand_CanExecute));
        }
        else
        {
            var cmd = selector
                        .CommandBindings
                        .Cast<CommandBinding>()
                        .SingleOrDefault(x => 
                            x.Command == ClearSelectionCommand);
            if (cmd != null)
                selector.CommandBindings.Remove(cmd);
        }
    }

    public static void ClearSelectionCommand_Executed(
        object sender, 
        ExecutedRoutedEventArgs e)
    {
        Selector selector = (Selector)sender;
        selector.SelectedIndex = -1;
    }

    public static void ClearSelectionCommand_CanExecute(
        object sender, 
        CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }
}

Example usage - XAML:

<Window x:Class="ClearSelectionBehaviorLibrary.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ClearSelectionBehaviorLibrary"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style x:Key="MyStyle" TargetType="Selector">
            <Setter 
                Property="local:SelectorBehavior.ClearSelectionOnCommand" 
                Value="True"/>
        </Style>
    </Window.Resources>
    <Grid>
        <DockPanel>
            <Button 
                DockPanel.Dock="Bottom"
                Content="Clear"
                Command="{x:Static local:SelectorBehavior.ClearSelectionCommand}"
                CommandTarget="{Binding ElementName=TheListBox}"/>
            <ListBox
                Name="TheListBox" 
                ItemsSource="{Binding MyData}" 
                Style="{StaticResource MyStyle}"/>
        </DockPanel>
    </Grid>
</Window>

Example usage - Code Behind:

public partial class Window1 : Window
{
    public List<string> MyData { get; set; }

    public Window1()
    {
        MyData = new List<string>
        {
            "aa","bb","cc","dd","ee"
        };
        InitializeComponent();
        DataContext = this;
    }
}
Aviad P.
Worked like a charm thank you very much!
Russ