2015-12-15 88 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