首先,想問大家一個問題,你們如果要給一個Button添加背景圖片會怎么做?(呵呵,這個問題又點小白哈)
是這樣嗎?
<Button Height="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代碼如下:
<Button Name="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("模板名稱");
呵呵,很簡單吧?其實我還有另外一個問題,也同樣想征求大家的建議?我寫了觸發器,就是鼠標放上去會改變背景,直接鼠標操作沒問題,但是在觸屏上就需要點擊兩次才能執行不知道是什么狀況,把觸發器去了就沒事了……希望大神點意見……