2015-12-15 83 views
4

我在app.xaml中有一個模板。在運行期間,我想創建一個按鈕並應用此模板。我也想在運行時設置圖像源。在運行時設置圖像WPF

<Application.Resources> 
     <ControlTemplate x:Key="btemp2" TargetType="{x:Type Button}"> 
      <Image x:Name="myimage" HorizontalAlignment="Center" Height="84" VerticalAlignment="Center" Width="100" Margin="10,-17.5,7,-24.5" Stretch="UniformToFill"/> 
     </ControlTemplate> 
    </Application.Resources> 

運行時代碼:

Button newButton = new Button(); 
newButton.Width = 100; 
newButton.Height = 50; 
newButton.Template = (ControlTemplate)TryFindResource("btemp2"); 
System.Windows.Controls.Image i = newButton.Template.FindName("myimage",this) as System.Windows.Controls.Image; 

Bitmap bmp = GetIconImageFromFile(fileName); 
BitmapSource src = GetBitmapImageFromBitmap(bmp); 
i.Source = src; 
stack.Children.Add(newButton); 

預期它不工作。 斷點沒有達到

Bitmap bmp = GetIconImageFromFile(fileName); 
+1

因此,讓我們知道什麼是你的問題。 – AntiHeadshot

+1

它不工作大聲笑。斷點不會到達位圖bmp = GetIconImageFromFile(fileName); – RStyle

+0

然後把它放到你的問題中,這樣ppl可以讀取它並直接看到你的問題是什麼。 – AntiHeadshot

回答

4

您可以使用Binding設置圖像。所以你應該改變ControlTemplate。在那個例子中,我們使用ButtonTag屬性來設置圖像Source

<ControlTemplate x:Key="btemp2" TargetType="{x:Type Button}"> 
    <Image x:Name="myimage" HorizontalAlignment="Center" Height="84" VerticalAlignment="Center" Width="100" Margin="10,-17.5,7,-24.5" Stretch="UniformToFill" 
        Source="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Tag}"/> 
</ControlTemplate> 

Button創建的代碼應該看起來像這樣。

Button newButton = new Button(); 
newButton.Width = 100; 
newButton.Height = 50; 
newButton.Template = (ControlTemplate)TryFindResource("btemp2"); 
tempGrid.Children.Add(newButton); 
BitmapImage image = new BitmapImage(new Uri("pack://application:,,,/WPFTest;component/Images/GPlus.png")); 
newButton.Tag = image; 
+0

綁定應該是一條可行的路。 – AntiHeadshot

+0

非常感謝。最後工作。是否有任何推薦書閱讀wpf與C#? – RStyle

+0

不客氣。 「Wpf釋放」是非常有用的書。 – bars222

1

刪除this,並在下面的代碼使用newButton,並處理Loaded事件:

Grd.Children.Add(newButton); 
    newButton.Loaded += newButton_Loaded; 
    ... 


void newButton_Loaded(object sender, RoutedEventArgs e) 
     { 
      Image img = (Image)newButton.Template.FindName("myimage", newButton); 
      ... 
     } 
+0

這將返回null而不是拋出異常。所以他仍然無法爲此設置來源。 – AntiHeadshot

+0

是的,我試過,沒有工作 – RStyle

+0

@RStyle請檢查更新的答案。 – AnjumSKhan