如何正确更改我刚刚点击的按钮图像?

时间:2011-12-08 09:57:46

标签: c# multithreading silverlight windows-phone-7

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

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

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

以下是点击事件的代码:

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

        }
    }
}

1 个答案:

答案 0 :(得分:0)

它发生的原因 - Button有一个操纵background属性的视觉状态。当您尝试将背景设置为您自己的时候 - 动画会覆盖您的更改。如果从视觉状态中删除背景动画 - 它将在没有延迟的情况下工作。