Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用System.Windows.Forms.ImageList的WPF按钮_C#_Wpf - Fatal编程技术网

C# 使用System.Windows.Forms.ImageList的WPF按钮

C# 使用System.Windows.Forms.ImageList的WPF按钮,c#,wpf,C#,Wpf,有没有一个很好的方法可以做到以下几点。获取WPF按钮和Windows.Forms.ImageList并将它们一起使用。代码如下: <Button Name="SOMETHING" Content="Button" Height="23" VerticalAlignment="Top" Width="75"/> System.Windows.Forms.ImageList imgList = new System.Windows.Forms.ImageList();

有没有一个很好的方法可以做到以下几点。获取WPF按钮和Windows.Forms.ImageList并将它们一起使用。代码如下:

    <Button Name="SOMETHING" Content="Button" Height="23" VerticalAlignment="Top" Width="75"/>

    System.Windows.Forms.ImageList imgList = new System.Windows.Forms.ImageList();

    string str_directory = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
    this.imgList.Images.Add(System.Drawing.Image.FromFile(str_directory + "\\Resources\\AboutImage.png"));
    WPFbutton.Background = imgList.Images[0];

System.Windows.Forms.ImageList imgList=新的System.Windows.Forms.ImageList();
string str_directory=System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.directory.GetCurrentDirectory());
this.imgList.Images.Add(System.Drawing.Image.FromFile(str_目录+“\\Resources\\AboutImage.png”);
WPFbutton.Background=imgList.Images[0];

我正在获取Windows.Forms ImageList并在WPF按钮上使用它。有什么好办法可以解决它吗?

不需要图像列表。只需按照下面的代码所示执行,该代码假定路径“Resources\AboutImage.png”是相对于应用程序的当前工作目录的

显然,您已经调用了两次
Path.GetDirectoryName
,以切断路径的“bin\Debug”或“bin\Release”部分,从而直接从Visual Studio项目结构访问图像文件。当应用程序部署到其他地方时,这将不起作用。相反,将图像文件的构建操作设置为内容,并将复制到输出目录设置为始终复制,或复制(如果更新)

var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "AboutImage.png");
var bitmap = new BitmapImage(new Uri(path));
WPFbutton.Background = new ImageBrush(bitmap);

但是,更好的方法是直接加载图像资源。设置并通过以下方式加载图像:

除此之外,您通常会使用XAML设置背景,如:

<Button ...>
    <Button.Background>
        <ImageBrush ImageSource="/Resources/AboutImage.png"/>
    </Button.Background>
</Button>


不要混合使用WPF和Windows窗体。这不是个好主意。选择WPF或WinFormsM我的第一个问题是为什么,在你眼中,将图像作为图像列表的一部分有什么好处。@Clemens中的示例应该会有所帮助,但您也可以简单地在XAML上实现,您的按钮可以有一个包含和图像以及文本的stackpanel,或者您喜欢的任何内容(只要您不将内容添加为属性,而是作为按钮语法的一部分,如:
<Button ...>
    <Button.Background>
        <ImageBrush ImageSource="/Resources/AboutImage.png"/>
    </Button.Background>
</Button>