How to create a context menu on DataGrid’s row, and add an icon

Took me a while to figure this out.

So I’m adding a context menu to rows of DataGrid.

This is the markup (taken from SavePoint):

 

<DataGrid Name="dgSavePoints" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1"

	  AutoGenerateColumns="False" ItemsSource="{Binding SavePoints}"

	  AlternatingRowBackground="GhostWhite"  AlternationCount="2" IsReadOnly="True" SelectionMode="Single" Margin="5" KeyUp="dgSavePoints_KeyUp">

	<DataGrid.Resources>

		<ContextMenu x:Key="DataRowContextMenu">

			<MenuItem Name="mnuRestore" Header="Restore"  Click="mnuRestore_Click" >

				<MenuItem.Icon >

					<Image Source="/SavePoint;component/Images/Restore.png" Width="20" Height="20"></Image>

				</MenuItem.Icon>

			</MenuItem>

			<MenuItem Name="mnuDelete"  Header="Delete" Click="mnuDelete_Click" >

				<MenuItem.Icon >

					<Image Source="/SavePoint;component/Images/Delete.png" Width="20" Height="20"></Image>

				</MenuItem.Icon>

			</MenuItem>

			<MenuItem  Name="mnuDeleteAll" Header="Delete all" Click="mnuDeleteAll_Click" >

				<MenuItem.Icon >

					<Image Source="/SavePoint;component/Images/DeleteAll.png" Width="20" Height="20" ></Image>

				</MenuItem.Icon>

			</MenuItem>

		</ContextMenu>

	</DataGrid.Resources>



	<DataGrid.RowStyle>

		<Style TargetType="{x:Type DataGridRow}" x:Name="styleForDataRow">

			<Setter Property="ContextMenu" Value="{StaticResource DataRowContextMenu}">

			</Setter>

		</Style>

	</DataGrid.RowStyle>



	<DataGrid.Columns>

		<DataGridTextColumn Header="Document" Binding="{Binding DocumentRelativePath}" Width="auto"></DataGridTextColumn>

		<DataGridTextColumn Header="Project" Binding="{Binding ProjectName}" Width="auto"></DataGridTextColumn>

		<DataGridTextColumn Header="Date Saved" Binding="{Binding DateSaved, StringFormat=d MMM yyyy HH:mm:ss}" Width="auto"></DataGridTextColumn>

		<DataGridTextColumn Header="Description" Binding="{Binding Description}" Width="*"></DataGridTextColumn>

	</DataGrid.Columns>

</DataGrid>
 
Now, see the the Image Source  property ?
I was setting this manually to “Images/image.png”. Don’t do this! Instead, click on Source of a Properties pane, and select the image you want – it will set the correct path.
 
 

Leave a Reply

Your email address will not be published. Required fields are marked *