繁体   English   中英

如何从其他名称空间更改图像源?

[英]How do I change an image source from a different namespace?

我是C#的新手,所以请原谅似乎是newb的问题:我目前在弄清楚如何从其他名称空间更改MainWindow上的图像方面遇到困难。 这是我遇到的问题的简化版本:

MainWindow.xaml:

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Image x:Name="imageToChange" Source="images/01.png" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" />
</Grid>

ChangeImage.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Test.DiffNamespace
{
    class ChangeImage
    {
        Test.MainWindow.imageToChange.Source="images\02.png";  //This doesn't work
    }
}

显而易见,MainWindow在Test下,而ChangeImage在Test.DiffNamespace下。 理想情况下,我希望这种方法无需更改结构即可工作,但是如果无法执行尝试操作,那么我仍然可以采用解决方法。

假设您要静态更新的解决方案

您的课程,具有指向图片的静态属性

class ChangeImage
{
    static ChangeImage()
    {
        Image = "images\02.png";
    }

    public static string Image { get; set; }
}

XAML,注意添加了名称空间“ diff”和图像源绑定

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:diff="clr-namespace:Test.DiffNamespace">
<Grid>
    <Image x:Name="imageToChange" 
           Source="{Binding Source={x:Static diff:ChangeImage.Image}}" 
           HorizontalAlignment="Left" 
           Height="100" 
           VerticalAlignment="Top" 
           Width="100" />
</Grid>

如果图像作为资源嵌入,则应使用以下代码

class ChangeImage
{
     // Test.MainWindow.imageToChange.Source="images\02.png";  //This doesn't work
    BitmapImage logo = new BitmapImage();
    logo.BeginInit();
    logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");
    logo.EndInit();
    Test.MainWindow.imageToChange.Source = logo;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM