我在app.xaml中有一个模板。在运行时,我想创建一个按钮并应用此模板。我还想在运行时设置图像源。

<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);

最佳答案

您可以使用Binding设置图像。因此,您应该更改ControlTemplate。在该示例中,我们使用Button Tag属性设置图像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;

10-06 06:30