Benjin
Benjin

Reputation: 2409

How can I change the text in a WPF menu item from the .cs file?

I'm learning WPF (this is my second day), and I'm trying to make a play/pause toggle menu item. The program starts paused, with the menu item reading "Start"; when I click "Start", I'd like the menu item to change to "Pause".

<MenuItem Header="_Server">
    <MenuItem Header="Start" Click="ToggleRunningStatus" Name="toggleRunningMenuItem" />
</MenuItem>

I was hoping it'd be as simple as toggleRunningMenuItem.SetText("Pause"); but that doesn't seem to be the case. Thanks for helping me out!

Upvotes: 4

Views: 5836

Answers (2)

Grant Winney
Grant Winney

Reputation: 66439

You have the header in your XAML set to "Start".

You can access that same property from code-behind:

toggleRunningMenuItem.Header = "Pause";

You don't even need to set a name for the menu:

private void ToggleRunningStatus(object sender, RoutedEventArgs e)
{
    var menuItem = (MenuItem)e.OriginalSource;
    menuItem.Header = "Pause";
}

Upvotes: 7

Ethan Brouwer
Ethan Brouwer

Reputation: 1005

Try changing the Name attribute to x:Name so:

<MenuItem Header="Start" Click="ToggleRunningStatus" x:Name="toggleRunningMenuItem" />

Upvotes: 1

Related Questions