Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event fired when item is added to ListView?

Tags:

wpf

I have this XAML:

<ListView Name="NameListView"
          HorizontalAlignment="Stretch"
          VerticalAlignment="Stretch"
          Grid.Column="1">
    <ListView.View>
        <GridView>
            <GridViewColumn>
                <GridViewColumn.DisplayMemberBinding>
                    <MultiBinding StringFormat="{}{0} {1}">
                        <Binding Path="First" />
                        <Binding Path="Last" />
                    </MultiBinding>
                </GridViewColumn.DisplayMemberBinding>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

and an ObservableCollection<Name> called "names" binded to the ListView in my code-behind. When a new new name is added to the collection, I want the ListView to change the background color of that newly added name. How do I go about doing it?

like image 410
boyla001 Avatar asked May 05 '11 21:05

boyla001


2 Answers

You can subscribe to the ItemsChanged event on your listbox.Items property. This is a little tricky because you have to cast it first. The code to subscribe would look like this:

((INotifyCollectionChanged)MainListBox.Items).CollectionChanged +=  ListBox_CollectionChanged;

And then inside that event you can get to your item with code like this:

private void ListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems.Count > 0)
        {
            Dispatcher.BeginInvoke(() =>
            {
                var newListItem = MainListBox.ItemContainerGenerator.ContainerFromItem(e.NewItems[0]) as Control;
                if (newListItem != null)
                {
                    newListItem.Background = System.Windows.Media.Brushes.Red;
                }
            }, DispatcherPriority.SystemIdle);
        }
    }
like image 54
Matt West Avatar answered Oct 21 '22 10:10

Matt West


Setting the background of a ListViewItem directly is not a good idea because by default a ListView is virtualizing (which is good), that means the controls that make up the items get disposed when scrolled out of view. The easiest way to do this is that i can think of is having a property in your data-object which indicates the New-state, then you can trigger on it.

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsNew}" Value="True">
                <Setter Property="Background" Value="Yellow"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ListView.ItemContainerStyle>

You then can use any logic you want to set that value to false again if you do not consider it new anymore.

like image 32
H.B. Avatar answered Oct 21 '22 09:10

H.B.