问题描述
我正在尝试在后台代码中设置图片背景.我尝试将背景图像添加到按钮上,但是当我将鼠标悬停在按钮上时,该图像就会消失.为了解决这个问题,我必须编写函数来覆盖按钮行为,这在后台代码中实在太多了.
I'm trying to set an image background in code-behind. I tried adding a background image to the button, but as soon as I hover over the button, the image disappears. To solve this, I have to write functions to override the button behavior, which is too much to do in code-behind.
然后,我使用另一种方法,即将按钮和图像分别添加到网格单元中.问题是-当我单击图像时,按钮不会触发.
I then use an alternative method, that is to add a button and an image separately to a grid cell. The issue is -- when I click on the image, the button won't trigger.
我如何使按钮具有悬停和按下效果,即使鼠标悬停或按下按钮上的图像,但按钮的剩余区域?
How do I make the button to have the hover and pressed effect, even when, the mouse is either hovering or presses the image on the button, but not the remaining area of the button?
或者希望有人可以为我提供更好的解决方案.下面是我的代码.
Or hope someone can suggest me a better solution.Below is my code.
InitializeComponent();
Button playBtn = new Button();
playBtn.Width = 60;
playBtn.Height = 30;
Image playIcon = new Image();
playIcon.Source = new BitmapImage(new Uri(@"PATH"));
playIcon.Stretch = Stretch.Uniform;
playIcon.Height = 25;
grid1.Children.Add(playBtn);
grid1.Children.Add(playIcon);
Grid.SetColumn(playBtn, 0);
Grid.SetRow(playBtn, 0);
Grid.SetColumn(playIcon, 0);
Grid.SetColumn(playIcon, 0);
感谢大家的投入,在进行了更多的研究之后,它才得以解决.我所做的是在 Button.Content 中添加 Grid ,然后将图像添加到Grid.然后使用不透明度为 IsEnable 错误状态添加变灰效果.在下面的代码中,希望有人觉得它有用或改进:
thanks for everyone input, after digging more into it, it sort of work out. What I did is add a Grid to Button.Content then add the image to the Grid. And using Opacity to add the grey out effect for IsEnable false state. Below I post my code, hope someone find it useful or improve on:
Button playBtn = new Button();
Image playIcon = new Image();
public MainWindow()
{
InitializeComponent();
Grid grid2 = new Grid();
RowDefinition grid2_row1 = new RowDefinition();
ColumnDefinition grid2_col1 = new ColumnDefinition();
grid2.RowDefinitions.Add(grid2_row1);
grid2.ColumnDefinitions.Add(grid2_col1);
playBtn.Width = 60;
playBtn.Height = 30;
playBtn.Click += playBtn_Click;
playIcon.Source = new BitmapImage(new Uri(@"pack://PATH..."));
playIcon.Stretch = Stretch.Uniform;
playIcon.Height = 25;
playBtn.Content = grid2;
grid2.Children.Add(playIcon);
grid1.Children.Add(playBtn);
Grid.SetRow(playIcon, 0);
Grid.SetColumn(playIcon, 0);
}
public void playBtn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello");
}
private void button1_Click(object sender, RoutedEventArgs e)
{
playBtn.IsEnabled = false;
playIcon.Opacity = 0.3;
}
推荐答案
检查以下链接
http://www.hardcodet. net/2009/01/create-wpf-image-button-through-attached-properties
http://social.msdn.microsoft.com/Forums/zh-CN/wpf/thread/91df562f-414c-4326-ac65-42ef301b5f8f/
这篇关于C#代码后面的图像按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!