如何正确地改变一个按钮的图像,我刚刚点击

本文关键字:图像 按钮 一个 改变 正确地 | 更新日期: 2023-09-27 18:17:04

这是我的困境。我有一组10个按钮,我用来评价一些东西。它们有一个星形图像,当按下时,它会从灰色变成红色。如果我按下星号5,所有之前的也会变成红色。

我的问题是,被点击的星号不会改变它的图像,所以我找到了一个解决方案,在调度程序块内引入暂停。我不认为这很优雅,但它有效,我想知道是否有人有更好的方法。

即使没有人找到更好的方法,至少这段代码将帮助其他人使用几乎相同功能的多个按钮或浏览面板中的控件。

下面是click事件的代码:
private void btnStar_Click(object sender, RoutedEventArgs e)
    {
        //First we get the number of the star from the control name
        String strNum = (sender as Button).Name;
        strNum = strNum.Replace("btnStar", "");
        int idxSelected = int.Parse(strNum);
        Debug.WriteLine("Selected star #" + strNum);
        //We store the image ON an OFF to be used later
        ImageBrush imgbrON = new ImageBrush();
        imgbrON.ImageSource = new BitmapImage(new Uri("images/estrella_on.png", UriKind.Relative));
        imgbrON.Stretch = Stretch.None;
        ImageBrush imgbrOFF = new ImageBrush();
        imgbrOFF.ImageSource = new BitmapImage(new Uri("images/estrella_off.png", UriKind.Relative));
        imgbrOFF.Stretch = Stretch.None;
        //If we pressed the first star when only the first was selected we reset all
        if (idxSelected == 1 && iCurrentNumberOfStars == 1)
        {
            idxSelected = 0; //In order to deselect all stars
            Debug.WriteLine("Deselect all");
        }
        else
        {
            //Here is the code to do the WORKAROUND to select the clicked star
            Dispatcher.BeginInvoke(() =>
           {
               Thread.Sleep(500);
               (sender as Button).Background = imgbrON;
           });
        }
        iCurrentNumberOfStars = idxSelected;

        foreach (UIElement child in ContentPanel.Children)
        {
            Thread.Sleep(10);
            if (child.GetType().Name == "Button")
            {
                Button tmpButton = (child as Button);
                Image content = tmpButton.Content as Image;
                strNum = tmpButton.Name;
                if (strNum.StartsWith("btnStar") == true)
                {
                    strNum = strNum.Replace("btnStar", "");
                    int idxtmp = int.Parse(strNum);
                    if (idxtmp > idxSelected )
                    {                       
                        Debug.WriteLine(tmpButton.Name + ":OFF");
                        tmpButton.Background = imgbrOFF;
                    }
                    else
                    {                            
                        Debug.WriteLine(tmpButton.Name +":ON");
                        tmpButton.Background = imgbrON;
                    }
                }
            }
        }
    }
}

如何正确地改变一个按钮的图像,我刚刚点击

它发生的原因-按钮有一个视觉状态来操纵背景属性。当您尝试将背景设置为自己的背景时,动画将覆盖您的更改。如果你从视觉状态中删除背景动画-它将工作没有延迟