wpflistviewgridviewcolumn

Images contained in the buttons disappear after adding a new item to the WPF listview


Within a GridViewColumn in a listView I have three buttons (delete, move up and move down item) in the same column. Delete button will always be shown. However Move Up and Move down buttons are collapsed or not depending if they have sense (for example, if the listview only has 1 item, only delete button will be shown, if it has more than 1 item, first item only shows delete and move down buttons and last item, delete and move up buttons). The look of the buttons are as below (I post here only one):

<Image x:Key="ImgDelete" Source="pack://application:,,,/Sys;component/Resources/ImageDelete.png"

<Button Content="{StaticResource ImgDelete}"
        Margin="10 0 0 0"
        Height="24"
        Width="24"
        VerticalAlignment="Stretch" 
        HorizontalAlignment="Stretch"
        Command="{Binding Path=DataContext.DeleteCommand, ElementName=myListView}"                             
        CommandParameter="{Binding (ItemsControl.AlternationIndex),
                           RelativeSource={RelativeSource AncestorType=ListViewItem}}"/>

The buttons contain a 24x24 png image as you can see above.

Also in the first row of the ListView I have an "Add" button to add items to the ListView. Initially the ListView is empty.

I add first item to the listview and it is added correctly, the button with the image inside is shown. See below:

enter image description here

Then I add a second item to the listview and this is added correctly, the button with its image is shown BUT the previous item I added before to the listview (the first one), its delete and move down buttons are shown BUT with no image inside (the image has disappeared). See below:

enter image description here

If I add another item to the listview:

enter image description here

and so on....

As you see, when adding a new item to the listview, in all the previous ones the image of the buttons disappears.

Any ideas what's happening?


Solution

  • An instance of Image is required for each instance of Button.

    So add derived class of BitmapSource such as BitmapImage in Window.Resources and elsewhere and refer it from each Image instance. In addition, I would recommend to set PresentationOptions:Freeze in the BitmapImage.

    <BitmapImage x:Key="ImageDeleteKey"
                 UriSource="Resources/ImageDelete.png"
                 PresentationOptions:Freeze="True"/>
    
    <Button>
        <Image Source="{StaticResource ImageDeleteKey}"/>
    </Button>
    

    EDIT:

    The solution suggested by Clemens x:Shared="False" also works. In comparison with that solution, this solution will be better in memory efficiency (less memory usage) but the practical impact will depend on the size of image file.