[英]Change button image on click in wpf c#
我正在使用xaml和c#為Windows 8.1存儲創建井字游戲,並試圖更改單擊時的X和O按鈕。 最初,我在按鈕的xaml中設置了一個空白圖像,並且在button_click事件中,我嘗試更改圖像源。 這是我的代碼片段:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if (turn == 1)
{
BitmapImage bmp = new BitmapImage();
Uri u = new Uri("ms-appx:/Images/O_logo.png", UriKind.RelativeOrAbsolute);
bmp.UriSource = u;
ImageBrush i = new ImageBrush();
i.ImageSource = bmp;
btn.Background = i;
}
else
{
BitmapImage bmp = new BitmapImage();
Uri u = new Uri("ms-appx:/Images/X_logo.png", UriKind.RelativeOrAbsolute);
bmp.UriSource = u;
ImageBrush i = new ImageBrush();
i.ImageSource = bmp;
btn.Background = i;
}
btn.IsEnabled = false;
//win(btn.Content.ToString());
turn += 1;
if (turn > 2)
turn = 1;
}
我已經在線閱讀了幾篇文章,其中一些文章建議將映像的構建操作設置為Resource,但是我沒有這個選擇。 我可以選擇PRIResource和Embedded Resource。 我對mvvm和觸發器的了解非常有限,因此想使用wpf本身而不是在xaml中解決問題。
我正在使用VS Studio Professional 2013
禁用按鈕時不顯示Background
。 您應該將Image
作為按鈕內容:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if (turn == 1)
{
BitmapImage bmp = new BitmapImage();
Uri u = new Uri("ms-appx:/Images/O_logo.png", UriKind.RelativeOrAbsolute);
bmp.UriSource = u;
// NOTE: change starts here
Image i = new Image();
i.Source = bmp;
btn.Content = i;
}
else
{
BitmapImage bmp = new BitmapImage();
Uri u = new Uri("ms-appx:/Images/X_logo.png", UriKind.RelativeOrAbsolute);
bmp.UriSource = u;
// NOTE: change starts here
Image i = new Image();
i.Source = bmp;
btn.Content = i;
}
btn.IsEnabled = false;
//win(btn.Content.ToString());
turn += 1;
if (turn > 2)
turn = 1;
}
我也強烈建議您學習並開始使用XAML和綁定,而不要避免使用它。 實際上,您正在以使用WPF的方式“與之抗爭”,並使WPF變得更加困難。 如果按預期使用它,您可能會發現它優於Windows Forms。
我在WPF中做了非常相似的事情,不是井字游戲,但是有多個數據網格,每個數據網格具有完全不同的背景並占據了相同的位置,然后使用按鈕啟用/禁用。 我會寫下一些代碼,但我不知道wpf像winforms一樣容易動搖,而且它們非常不同(主要區別是wpf是比較廢話)。
但是類似:
button1_click(object sender, EventArgs e)
{
if (turn == 1)
{
gridX.Visibility = visible;
}
else
{
gridO.Visibility = visible;
}
button1.Visibility = hidden;
}
然后只需將圖像放入網格,標簽或w / e
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.