blah blah blah is here! blah blah » Close

up0down
link

i'm looking to compare button content in wpf

i have a button with "Start" written in it, i need it to change to "Stop" in code, so i tried this:

if (btnStart.Content.ToString() == "Start")

{
btnStart.Content = "Stop";
}


this doesn't work. any ideas?

last answered 2 years ago

3 answers

link

the original code, at the first post i made, is in fact the answer. i had a button that was similarly named, so intellisense brought up the incorrect, yet similar, named button. thanks

up0down
link

If that code doesn't work, then the only conclusion I can draw is that btnStart's Content isn't currently "Start".

I'd check capitalization and that you haven't included any leading or trailing spaces.

up0down
link

Chances are, the content isn't actually a string but is actually wrapped in a TextBlock. I don't recall if calling ToString() on a block would return the string it represents (just a generic "System.Windows.Controls.TextBlock") causing problems as it doesn't look like it overrides. If it's just a simple string in the block (i.e., unformatted), you should compare against the TextBlock's Text instead. You'd also want to modify the text block directly or store a new one in the button.

TextBlock tb = btnStart as TextBlock;
if (tb != null && tb.Text == "Start")
{
tb.Text = "Stop";

//or
btnStart.Content = new TextBlock("Stop");
}

Feedback