1

我提到了这个,写了几乎相同的代码,但用不同的语言,它没有按预期工作!
我使用 winform(C++/Cli) 作为主机 & 'WPF User Control Libaray'(C#) 作为子控件。
使用 Winform 中的 ElementHost 组件在 Winforms 中集成 WPF 用户控件(PictureBox)。
基本上我想从winform按钮更改WPF控件中的图片。它编译并运行良好。
但唯一的问题是即使图片路径正确,图像也不会改变。

下面的代码在 winform button_click 事件中

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    OpenFileDialog ^ofd = gcnew OpenFileDialog();
    WpfControlLibrary1::UserControl1 ^uc = gcnew UserControl1();
    if (ofd->ShowDialog() == Windows::Forms::DialogResult::OK)      
    uc->open(ofd->FileName);        
}

下面的代码在 UserControl1.xaml.cs

public void open(string path)
{
    MessageBox.Show(path); //path seems to be fine
    img.Source = new BitmapImage(new Uri(path));
}

下面的代码在 UserControl1.xaml

<UserControl x:Class="WpfControlLibrary1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid Margin="-54,0,0,0">
        <Image x:Name="img"  Stretch="Uniform" Opacity="1" Source="Koala.jpg"/>
    </Grid>
</UserControl>

尝试在 xaml 代码中删除源图像,它没有效果

4

1 回答 1

2

该声明

WpfControlLibrary1::UserControl1 ^uc = gcnew UserControl1();

创建一个新的 UserControl1 实例。这不是您之前放入 ElementHost 的实例,因此不会显示在您的 UI 中。

于 2016-07-17T13:03:19.743 回答