在运行时WPF中设置图像

时间:2015-12-15 07:05:00

标签: wpf

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

dst

运行时代码:

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

2 个答案:

答案 0 :(得分:4)

您可以使用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;

答案 1 :(得分:1)

删除this,并在下面的代码中使用newButton,并处理已加载的事件:

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


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