一般我們在開發Windows Store App 或 Windows Phone App ,有時會去調整控制項的透明度就是Opacity 的屬性,再利用IF判斷是去判斷該控制項是否在某一個自訂的透明度,去做相對應的事情,可是當我們使用 Opacity = = .X的時候,不可思議的事情發生了。

本篇文章將引導您增加對Opacity 透明度屬性的認識。

 

我們在舞台上新建一個按鈕 Button ,並在程式碼中設定該按鈕的透明度為 0.2 也就是顯示20%的意思。

 

Xaml :

 <Button x:Name="BTN" Content="透明度測試" Click="Button_Click" />

 

C#

BTN.Opacity = 0.2;

 

設定完之後,再新增一個判斷式,利用按鈕觸發,

判斷若透明度為0.2的話就改變成1

若透明度為 1的畫改為0.2

0.2→1

1→0.2

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (BTN.Opacity == 0.2)
    {
        BTN.Opacity = 1;
    }
    if (BTN.Opacity == 1) {
        BTN.Opacity = 0.2;
    }
}

運行後會發現 怎麼樣也無法將透明度改為1

於是SUKI百思不得其解,索性將透明度直接 Debug.WriteLine()出來

 

於是連按兩次按鈕的透明度結果如下

 

1
0.200000002980232

 

也就是非常神奇的事情發生了,透明度竟然不是0.2

而是0.200000002980232,

其中的原因是因為 那是因為浮點數不是精確小數的關係(感謝Phoenix補充說明),

而且在 http://msdn.microsoft.com/zh-tw/library/system.double.ASPX

也提到了 “由於某些數字不能表示為小數的二進位值,浮點數可能只是大約的數目。

所以Opacity 透明度屬性並不是能如我們所願的非常精準

若日後有寫到修改控制項透明度屬性Opacity 時

要多加注意判斷式的修改,而不是Opacity ==0.2這麼簡單。

 

References : SUKI本人悟出來的

 

文章中的敘述如有觀念不正確錯誤的部分,歡迎告知指正 謝謝
http://www.sukitech.com/?p=940
轉載請註明出處,並且附上本篇文章網址 !  感謝。

21 Thoughts on “C# Windows Store App,Windows Phone App 開發,控制項屬性 Opacity 透明度屬性的迷思。

  1. Thank you for your blog post.Thanks Again. Cool.

  2. Very good article post.Really thank you! Keep writing.

  3. Thanks a lot for the blog post.Really thank you! Awesome.

  4. Very informative post.Really looking forward to read more. Cool.

  5. I really like and appreciate your post.Really looking forward to read more. Really Cool.

  6. I really liked your blog post.Really thank you! Keep writing.

  7. Very informative blog article.Really thank you! Awesome.

  8. I think this is a real great post. Cool.

  9. Very good post.Thanks Again. Will read on…

  10. Major thanks for the blog post.Really thank you! Keep writing.

  11. Im grateful for the blog article.Really looking forward to read more. Really Cool.

  12. Very neat article post. Fantastic.

  13. Really appreciate you sharing this blog article.Really looking forward to read more. Really Cool.

  14. Thanks a lot for the blog.Thanks Again. Fantastic.

  15. Very informative blog article.Really looking forward to read more. Will read on…

  16. I really liked your blog post.Really thank you! Really Cool.

  17. I appreciate you sharing this article post.Thanks Again. Really Great.

  18. I really liked your article.Thanks Again. Keep writing.

  19. I loved your article.Really looking forward to read more. Awesome.

  20. Say, you got a nice blog article.Really looking forward to read more. Cool.

發表迴響

你的電子郵件位址並不會被公開。

Post Navigation