Ershad
Ershad

Reputation: 957

Listbox item as Listbox should clear the selection of its item when other item's item is selected?

I have a ListBox as a ListboxItem in the mainlist. In one item that is ListBox I select an item. This selection should be cleared when I have another item selected from the other items ListBox. Code is as below:

<ListBox x:Name="lst" Grid.Row="3" BorderThickness="0" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ItemsSource="{Binding MessageCollection}"  ScrollViewer.CanContentScroll="False" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical"  Width="{Binding RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type Grid}},Path=ActualWidth}" HorizontalAlignment="Stretch">
                <Border  Background ="#ffffff" BorderBrush="#dddddd" BorderThickness="0,1,0,0" Height="30" >
                    <TextBlock Text="{Binding Date, StringFormat={}{0:dd MMMM yyyy}}" VerticalAlignment="Center" FontWeight="Bold" FontSize="12" FontFamily="Tahoma"  Foreground="#7a7a7a" HorizontalAlignment="Center" />
                </Border>

                    <ListBox x:Name="lstMsgs" HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden"  HorizontalContentAlignment="Stretch"  ItemsSource="{Binding MessageList}" SelectedItem="{Binding DataContext.SelectedMessage,Mode=TwoWay,ElementName=me}" Background="Transparent" BorderThickness="0">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Border x:Name="brdItem" BorderBrush="#dddddd" BorderThickness="0,1,0,0" >
                                    <Border.Background>
                                        <LinearGradientBrush  StartPoint="0,0" EndPoint="0,1">
                                            <GradientStop Color="#f1f1f1" Offset="0"/>
                                            <GradientStop Color="#efefef" Offset="1"/>
                                        </LinearGradientBrush>
                                    </Border.Background>

                                    <Grid Height="30" HorizontalAlignment="Stretch" VerticalAlignment="Center" ScrollViewer.HorizontalScrollBarVisibility="Hidden"  >
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="10" />
                                                <ColumnDefinition Width="30" />
                                                <ColumnDefinition Width="10" />
                                                <ColumnDefinition Width="120" />
                                                <ColumnDefinition Width="10" />
                                                <ColumnDefinition Width="*" />
                                                <ColumnDefinition Width="10" />
                                                <ColumnDefinition Width="100" />
                                                <ColumnDefinition Width="30" />
                                            </Grid.ColumnDefinitions>
                                            <Image x:Name="img" Grid.Column="1" Visibility="Collapsed"  HorizontalAlignment="Center" Source="Images\icon1.png" Stretch="None" Margin="10,0,0,0"  />
                                            <TextBlock Text="Ershad Sheikh" VerticalAlignment="Center" Foreground="#2b2a2a" FontSize="12" Grid.Column="3" />
                                            <TextBlock Text="{Binding GroupMessage}" HorizontalAlignment="Left" Foreground="#7a7a7a" FontSize="11"  Grid.Column="5" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
                                            <TextBlock Text="{Binding Date, StringFormat={}{0: hh:mm:ss tt}}" FontWeight="Bold" FontSize="12" Foreground="#2378a0"  Grid.Column="7" VerticalAlignment="Center" HorizontalAlignment="Right" />
                                        </Grid>
                                    </Border>
                                    <DataTemplate.Triggers>
                                        <DataTrigger Binding="{Binding Path=IsReplyPresent}" Value="True">
                                            <Setter TargetName="img" Property="Visibility" Value="Visible" />
                                        </DataTrigger>
                                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True">
                                            <Setter TargetName="brdItem" Property="Background" Value="#e5e9eb" >                                                    
                                            </Setter>
                                        </DataTrigger>
                                    </DataTemplate.Triggers>
                                </DataTemplate>
                            </ListBox.ItemTemplate>

                            <ListBox.Resources>
                                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
                     Color="#e5e9eb"/>
                                <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" 
                     Color="Transparent" />
                                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/>
                            </ListBox.Resources>
                        </ListBox>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
                       Color="#e5e9eb"/>
                <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" 
                     Color="Transparent" />
            </ListBox.Resources>
        </ListBox>

Upvotes: 0

Views: 645

Answers (1)

Anand Murali
Anand Murali

Reputation: 4109

You can explicitly null the SelectedItem whenever the ListBox loses focus, i.e you have to handle the LostFocus event.

You could add the event handler to the ListBox and handle the event in the code behind.

XAML Change:

<ListBox x:Name="lstMsgs" HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden"  HorizontalContentAlignment="Stretch"  ItemsSource="{Binding MessageList}" SelectedItem="{Binding DataContext.SelectedMessage,Mode=TwoWay,ElementName=me}" Background="Transparent" BorderThickness="0" LostFocus="lstMsgs_LostFocus">

Code Behind:

    private void lstMsgs_LostFocus(object sender, RoutedEventArgs e)
    {
        ListBox listBox = sender as ListBox;
        if (listBox != null)
        {
            listBox.SelectedItem = null;
        }
    }

Method 2:

You could achieve the same result by using a DependencyProperty to handle the LostFocus event.

ListBoxExtension.cs

using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    public static class ListBoxExtension
    {
        public static readonly DependencyProperty NullSelectedItemOnLostFocusProperty =
            DependencyProperty.RegisterAttached("NullSelectedItemOnLostFocus", typeof(bool), typeof(ListBoxExtension), new UIPropertyMetadata(false, OnNullSelectedItemOnLostFocusChanged));

        public static bool GetNullSelectedItemOnLostFocus(DependencyObject d)
        {
            return (bool)d.GetValue(NullSelectedItemOnLostFocusProperty);
        }

        public static void SetNullSelectedItemOnLostFocus(DependencyObject d, bool value)
        {
            d.SetValue(NullSelectedItemOnLostFocusProperty, value);
        }

        private static void OnNullSelectedItemOnLostFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            bool nullSelectedItemOnLostFocus = (bool)e.NewValue;

            ListBox listBox = d as ListBox;
            if (listBox != null)
            {
                if (nullSelectedItemOnLostFocus)
                    listBox.LostFocus += NullSelectedItem;
                else
                    listBox.LostFocus -= NullSelectedItem;
            }
        }

        public static void NullSelectedItem(object sender, RoutedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox != null)
            {
                listBox.SelectedItem = null;
            }
        }
    }
}

XAML Change 1: Add namespace in which the ListBoxExtension class is present - xmlns:loc="clr-namespace:WpfApplication1"

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:loc="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">

XAML Change 2: Changing the DependencyProperty - loc:ListBoxExtension.NullSelectedItemOnLostFocus="True"

<ListBox x:Name="lstMsgs" HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden"  HorizontalContentAlignment="Stretch"  ItemsSource="{Binding MessageList}" SelectedItem="{Binding DataContext.SelectedMessage,Mode=TwoWay,ElementName=me}" Background="Transparent" BorderThickness="0" loc:ListBoxExtension.NullSelectedItemOnLostFocus="True">

Upvotes: 1

Related Questions