Search code examples
wpfpropertiestriggerslistboxdatatemplate

Create ListBoxItem property


I have two ListBox's and a Button. The Button sends List1.SelectedItems over to List2. I would like to add a visual cue for the items in List1 that have been added to List2, similar to how there is a visual cue when items are selected. Is it possible to add a property to them so that this can be accomplished?

 _______             _______
|       |     _     |       |
| List1 |    |>|    | List2 |
|_______|           |_______|

Here is an example of using the IsSelected property to modify the background.

<DataTemplate.Triggers> 
    <Trigger Property="IsSelected" Value="True"> 
        <Setter TargetName="listItem" Property="Background" Value="Blue" /> 
    </Trigger> 
</DataTemplate.Triggers>

I would like to add an additional property, called "IsAdded", which would also affect the background if set to True. Is something like that possible, or is there an alternative approach to this?

Thanks


Solution

  • I hope you use ViewModel class, or similar to this to represent you items. What you need - is to add the property IsAdded to the item class, and, when you handle Button.Click event (or more better - your ViewModel has ICommand property which inserts selected items in List1 to List2), you can sad to the selected items which was added to the List2 that they are was added.

    private bool isAdded;
    public bool IsAdded
    {
        get { return isAdded; }
        set
        {
            if (isAdded == value)
                return;
            isAdded = value;
            OnPropertyChanged("IsAdded");
        }
    }
    

    where OnPropertyChanged method will raise an PropertyChanged event of INotifyPropertyChanged interface (see msdn article).

    When you handle Button.Click, you know which elements to be added, so put this line of code there:

    ...
    foreach(var item in List1.SelectedItems)
    {
        item.IsAdded = true;
    }
    ...
    

    And than, add to your DataTemplate.Triggers collection the following trigger:

    <DataTrigger Binding="{Binding Path=IsAdded, Mode=OneWay}" Value="True">
        <Setter TargetName="listItem" Property="Background" Value="Red" />
    </DataTrigger>