Jonathan.
Jonathan.

Reputation: 55604

Toggle MenuItem in c#

I have a ContextMenu for a DataGrid that display items that have a property Deleted. One of the items in the ContextMenu needs to be Delete, but also you can Undelete items (the items remain in the list but have a red background if they are going to be deleted).

Currently I have this:

    <Style x:Key="DeleteMenuItemStyle" TargetType="{x:Type MenuItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Deleted}" Value="true">
                <Setter Property="Header" Value="Undelete"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding Deleted}" Value="false">
                <Setter Property="Header" Value="Delete"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

However I'm unsure how to toggle the Deleted Property on the item, currently I can only delete items, and the Click event handler for the item is:

    private void mnuDelete_Click(object sender, RoutedEventArgs e)
    {
        DatabaseIndex index = (DatabaseIndex)((MenuItem)sender).DataContext;
        index.Deleted = true;
    }

So whether the menuitem says Delete or Undelete the Deleted proeprty is set to to true atm. I could check what the sender's text is and then set true or false depending on that but this seems completely wrong to me, as if I change the text "Delete" and "Undelete" I have to change the code.

I could use an EventSetter in the style and have two different event handlers but they would be identical to each other except for the true and false.

What is the best way of doing this? Is there some way to like "bind the Click event to the Deleted property"?

Upvotes: 1

Views: 1499

Answers (1)

Moha Dehghan
Moha Dehghan

Reputation: 18472

Why not check the Deleted property itself?

private void mnuDelete_Click(object sender, RoutedEventArgs e)
{
    DatabaseIndex index = (DatabaseIndex)((MenuItem)sender).DataContext;
    if (index.Deleted)
    {
        index.Deleted = false;
        // code to undelete
    }
    else
    {
        index.Deleted = true;
        // code to delete
    }
}

Or if you just want to toggle the Deleted property:

index.Deleted = !index.Deleted;

Upvotes: 1

Related Questions