在运行时设置图像的 WPF

4

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

1
请告诉我们您的问题是什么。 - AntiHeadshot
1
它不起作用,哈哈。断点没有到达Bitmap bmp = GetIconImageFromFile(fileName)。 - RStyle
然后将其放入您的问题中,这样人们就可以阅读并直接看到您的问题所在。 - AntiHeadshot
2个回答

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

绑定应该是正确的方法。 - AntiHeadshot
非常感谢。终于成功了。有没有关于使用C#的WPF推荐的书籍? - RStyle
不客气。“Wpf Unleashed” 这本书非常有帮助。 - bars222
在代码后台,应该像这样创建一个WPF资源文件包URInew Uri("pack://application:,,,/WPFTest;component/Images/GPlus.png") - Clemens
我也是,因为不需要UriKind。 - Clemens

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

这将返回 null 而不是抛出异常。因此,他仍然无法设置源。 - AntiHeadshot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接