繁体   English   中英

xaml更改图像源

[英]xaml change image source

在C#中,我正在使用xaml设计器制作应用程序。

问题:如果我将图像源更改为另一个图像源,则没有出现:提示,如果已经定义了图像,则将其更改为“ NULL”(无图像)

我使用一种方法(我在网上找到了)将图像源(字符串)更改为图像(对象)。

我已经尝试过多次更改某些xaml图片的图像源的方法,只是将xaml中的图像源更改为另一个图像(我将其放入项目中),但是不幸的是,当我这样做时该图像不可见。

我使用的图像和方法如下:

ms-appx:///Assets/bank_employee.jpg”

imageFromXaml.Source = imgCreatedFromMethod.Source;

private static Image srcToImage(string source)   
{   
        Uri imageUri = new Uri(source);    
        BitmapImage imageBitmap = new BitmapImage(imageUri);   
        Image img = new Image();   
        img.Source = imageBitmap;    
        return img;
}

你们中的任何人都知道可能是什么问题吗?

我有一个类似的问题,这对我有用:

            var imageSource = new BitmapImage();
            imageSource.BeginInit();
            imageSource.StreamSource = memoryStream;
            imageSource.CacheOption = BitmapCacheOption.OnLoad;
            imageSource.EndInit();

您是否尝试过将XAML中的源绑定到URI,然后进行更新?

像这样:

<Image Source="{Binding ImageUri}" />

然后在您的数据上下文中的某处具有一个属性,如下所示:

public class myClass: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Uri imageUri;

    public Uri ImageUri
    {
        get
        {
            return imageUri;
        }
        set
        {
           imageUri = value;
           if(PropertyChanged != null)
           {
               PropertyChanged(this, new PropertyChangedEventArgs("ImageUri"));
           }
        }
    }
}

您是否已验证您的方法确实成功并返回了正确的图像源? 如果这样做,重新分配Source应该没有问题。 如果您将新创建的图像本身加载到UI中,它是否保留其源?

this.Content = imgCreatedFromMethod;  // where "this" is the window

顺便说一句,没有必要实现自己的转换功能。 如果您有一个可以用作XAML的字符串,则可以直接调用XAML解析器用来构建图像源的转换器:

using System.Globalization;
using System.Windows.Media;

string stringValue = ...

ImageSourceConverter converter = new ImageSourceConverter();
ImageSource imageSource = converter.ConvertFrom(
    null, CultureInfo.CurrentUICulture, stringValue);

也可以通过System.ComponentModel.TypeDescriptor.GetConverter(typeof(TypeToConvertTo))动态检索转换器实例(在这种情况下为ImageSourceConverter System.ComponentModel.TypeDescriptor.GetConverter(typeof(TypeToConvertTo))

如果您像TylerD87的答案中那样使用数据绑定,此转换也将自动完成。 您还可以查看触发器并以如下样式定义两个图像:

<Image>
    <Image.Style>
        <Style TargetType="Image">
            <Setter Property="Source" Value="original path" />
            <Style.Triggers>
                <Trigger ...>
                    <Setter Property="Source" Value="new path" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

暂无
暂无

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

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