在Silverlight 5中通过代码改变按钮的背景颜色

4
我希望当我点击按钮时,能够改变其背景颜色,使其从红色变为绿色,再变为红色等等。但是,当我点击按钮时,背景颜色并没有改变。以下是我尝试过的方法:
button4.Background.SetValue(BackgroundProperty,new SolidColorBrush(Colors.Red)); -> catastrophic error

button4.SetValue(BackgroundProperty,new SolidColorBrush(Colors.Red)); -> nothing

button4.Background = new SolidColorBrush(Colors.Red); -> nothing

第三种解决方案似乎最相关,但并不起作用。

第二和第三个解决方案对我来说都可以直接使用(Silverlight 5)。您是否对按钮模板进行了任何更改?此外,您应该知道,即使它起作用,更改也会相当微妙。按钮背景只会呈现轻微的粉红色调。这是由于Button类的默认模板实现方式造成的。 - Henrik Söderlund
好的,谢谢。有没有办法改变它的实现方式?或者我应该转向另一个解决方案,比如使用ImageButton? - Oliver
1
是的,您必须编辑按钮模板。最好的方法是使用Blend。以下是有关如何在Blend中构建圆形按钮模板的文章链接:http://www.codeproject.com/Articles/64937/Building-Better-Buttons-in-Expression-Blend-Silver - Henrik Söderlund
据我所知,Silverlight 中没有内置的 imagebutton。 - Henrik Söderlund
1个回答

4

我在Silverlight 5中遇到了与UserControl相同的问题。

protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
  base.OnMouseLeftButtonDown(e);
  Background = new SolidColorBrush(Colors.Black); //nothing
}

但是如果我将主网格命名为"grid"并写下以下代码:
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
  base.OnMouseLeftButtonDown(e);
  grid.Background = new SolidColorBrush(Colors.Black); //ok
}

它可以工作,但我不知道为什么。当我需要使用一些复杂的透明度效果时,也许我需要一些额外的矩形并设置它们的填充。这有点不方便。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接