Welcome

首页 / 软件开发 / .NET编程技术 / WPF学习备忘(5)怎样修改模板中的控件

WPF学习备忘(5)怎样修改模板中的控件2013-11-26 cnblogs 幕三少首先,想问大家一个问题,你们如果要给一个Button添加背景图片会怎么做?(呵呵,这个问题又点小白 哈)

是这样吗?

<ButtonHeight="57" HorizontalAlignment="Left" Margin="106,86,0,0" Name="button1" VerticalAlignment="Top" Width="147" BorderThickness="0"><Button.Background><ImageBrush ImageSource="/WpfProgressBarDemo;component/Images/btn_13.png" /></Button.Background></Button>
如果也是这样的话,那你们有没有碰到这个问题呢,当鼠标放到按钮上, 背景会被改变呢?如图:

正常显示

鼠标放到按钮上

按 钮就变成这样了,你们有没有碰到这样的事情?那你们又是怎么解决的呢,希望高手指点下。不胜感激……

我们的解决方案是做一个模板,把背景图片当作内容赋给Button代码如下:

<ButtonName="btnSure" Click="btnSure_Click" Margin="10" ><Button.Template><ControlTemplate x:Name="ctSure"><ContentControl> <Image Source="/Oland.HSS.InHospital;component/Pictures/maintenance/1.png"></Image></ContentControl></ControlTemplate></Button.Template></Button>
这样就可以解决了刚才的那个问题,你们有好的建议吗?

下 面又出现新的问题了,我想根据业务需要从后台改变按钮背景怎么办?呵呵,标题中的中的问题来(怎样修改 模板中的控件):

其实也简单,就直接上代码了:

private void Window_Loaded(object sender, RoutedEventArgs e){if (!IsInMaintenance){ControlTemplate template = btnSure.FindName("ctSure") as ControlTemplate;if (template != null){Image img = template.FindName("imgWork", btnSure) as Image;img.Source = new BitmapImage(new Uri(@"../Pictures/maintenance/3.png",UriKind.Relative));}}}
如果你把模板放在Resource里面你可以这样写

ControlTemplate template = (ControlTemplate)this.TryFindResource("模板名称");
呵呵,很简单吧?其实我还有另外一个问 题,也同样想征求大家的建议?我写了触发器,就是鼠标放上去会改变背景,直接鼠标操作没问题,但是在触 屏上就需要点击两次才能执行不知道是什么状况,把触发器去了就没事了……希望大神点意见……