在WPF中单击时更改按钮的嵌套图像的图像源

时间:2017-10-21 17:23:12

标签: c# .net wpf xaml

我有一系列按钮作为可切换的项目(超过2个状态)。我有一个方法来管理所有这些点击,但我还需要更新每个按钮中包含的图像,以便在每次点击时匹配它的状态。我的XAML看起来像这样:

<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>

然后我在后面看到了一些C#:

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";
    }
}

问题是我不知道如何引用每个包含元素的'Source'属性。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

嵌套Image元素可以通过Content属性访问(使用类型转换):

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 = "...";