0

I have a series of buttons that act as toggle-able items (with more than 2 states). I have a single method managing the click even on all of them, but I also need to update the image contained inside each button to match it's state every time they get clicked. My XAML looks like this:

<Button Name="Button1" Style="{StaticResource ImageButton}" Click="OnClick_MyButtonClick">
    <Image Name="Button1_Image_Default" Source="Images\Button1_Default"/>
</Button>

<Button Name="Button2" Style="{StaticResource ImageButton}" Click="OnClick_MyButtonClick">
    <Image Name="Button2_Image_Default" Source="Images\Button2_Default"/>
</Button>

<Button Name="Button3" Style="{StaticResource ImageButton}" Click="OnClick_MyButtonClick">
    <Image Name="Button3_Image_Default" Source="Images\Button3_Default" />
</Button>

I then have some C# in the back that looks like so:

void OnClick_MyButtonClick(object sender, RoutedEventArgs e)
{
    string buttonClicked = (sender as Button).Name;

    // filterDictionary is a Dictionary which contains the names and references of every button.
    int thisFilterCurrentValue = filterDictionary[buttonClicked];

    if (thisFilterCurrentValue == 0)
    {
        thisFilterCurrentValue++;
        //Psuedo Code:
        buttonClicked.Image.Source = "Images/buttonClickedOnce.gif";
    }

    if (thisFilterCurrentValue == 1)
    {
        thisFilterCurrentValue++;
        //Psuedo Code:
        buttonClicked.Image.Source = "Images/buttonClickedTwice.gif";
    }

    if (thisFilterCurrentValue == 2)
    {
        thisFilterCurrentValue = 0;
        //Psuedo Code:
        buttonClicked.Image.Source = "Images/buttonClickedThrice.gif";
    }
}

The issue is that I have no idea how to reference the 'Source' property of the element that each Contains.

How would I go about this?

1 Answer 1

1

nested Image element can be accessed via Content property (with type cast):

var btn = sender as Button;
if (btn == null) return;

string buttonClicked = btn.Name;

var img = btn.Content as Image;
if (img == null) return;

img.Source = "...";    
Sign up to request clarification or add additional context in comments.

1 Comment

@mkautzm, fixed. I try to avoid multiple as casts, because R# tends to underline them as possible NRE when variable is used on the next line. So I rewrote it a bit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.