2011-08-11 43 views
4

兩個按鈕這個按鈕行爲:爲什麼在WP7不同

<Button Content="Button" Height="72" HorizontalAlignment="Left" Margin="10,10,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" /> 
    <Button Content="Button" Height="72" HorizontalAlignment="Left" Margin="10,92,0,0" Name="button2" VerticalAlignment="Top" Width="160" /> 

自我解釋代碼:

public MainPage() 
    { 
     InitializeComponent(); 
     button1.Background = new SolidColorBrush(Colors.Red);    
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     Color c = ((SolidColorBrush)((Button)sender).Background).Color; 

     if (c == Colors.Red) 
     { 
      c = Colors.Green; 
     } 
     else if (c == Colors.Green) 
     { 
      c = Colors.Blue; 
     } 
     else if (c == Colors.Blue) 
     { 
      c = Colors.Red; 
     } 
     else 
     { 
      c = Colors.Yellow; 
     } 

     ((Button)sender).Background = new SolidColorBrush(c); 
     button2.Background = new SolidColorBrush(c); 
    } 

在一個普通的Silverlight應用程序如預期寄託都工作的。然而,在Windows Phone 7中,完全相同的代碼行爲如下:

button1不會改變顏色(它只是保持紅色) button2確實會改變顏色,除非我點擊它,在這種情況下,當我點擊button1時它不再改變顏色(即它的顏色現在也卡住了)

線索enyone?

+0

在這裏多次。使用視覺狀態http://stackoverflow.com/questions/3476963/windows-phone-7-wp7-change-a-buttons-background-color-on-click –

+0

請參閱http://blogs.msdn.com/b/ ptorr/archive/2010/06/18/why-can-ti-change-the-background-of-my-button-on-a-click-event.aspx –

回答

1

之後應該做的伎倆:

var btn = sender as Button; 
var brush = ((SolidColorBrush)btn.Background); 

if (brush.Color == Colors.Red) 
    brush.Color = Colors.Green; 
else if (brush.Color == Colors.Green) 
    brush.Color = Colors.Blue; 
else if (brush.Color == Colors.Blue) 
    brush.Color = Colors.Red; 
else 
    brush.Color = Colors.Yellow; 

btn.Background = brush; 
button2.Background = brush; 
0

我會嘗試這樣設置按鈕的背景。這將運行(至少對我的理解)按鈕的線程在後臺代碼

 button2.Dispatcher.BeginInvoke(delegate 
     { 
      button2.Background = new SolidColorBrush(c); 
     }); 

我不知道這是否會解決任何事情,但它是值得一試。

-Woody

+0

嘗試過 - 沒有運氣 – descf

+0

那麼我有沒有。對不起 – Woody

+0

謝謝你的嘗試! – descf