C# xaml更改图像源
在c语言中,我正在使用xaml设计器制作一个应用程序 问题:如果我将图像源更改为另一个图像源,则不会显示任何内容:但是,如果该图像已定义,则会更改为空无图像 我使用了在web上找到的方法将imagesource字符串更改为imageobject 我曾多次尝试通过将xaml中的imagesource更改为我放入项目中的另一个图像来更改某些xaml图片的图像源,但不幸的是,这样做时图像不可见 我使用的图像和方法如下: ms-appx:///Assets/bank_employee.jpgC# xaml更改图像源,c#,image,xaml,C#,Image,Xaml,在c语言中,我正在使用xaml设计器制作一个应用程序 问题:如果我将图像源更改为另一个图像源,则不会显示任何内容:但是,如果该图像已定义,则会更改为空无图像 我使用了在web上找到的方法将imagesource字符串更改为imageobject 我曾多次尝试通过将xaml中的imagesource更改为我放入项目中的另一个图像来更改某些xaml图片的图像源,但不幸的是,这样做时图像不可见 我使用的图像和方法如下: ms-appx:///Assets/bank_employee.jpg image
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}" />
您是否验证了您的方法实际上成功并返回了正确的图像源?如果是这样的话,重新分配源应该没有问题。如果将新创建的图像本身加载到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.GetConvertertypeofTypeToConvertTo动态检索转换器实例ImageSourceConverter
如果使用中的数据绑定,此转换也将自动完成。您还可以按照以下样式查看和定义这两个图像:
<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>
是否缺少using指令或程序集引用?-显示此消息。你知道我应该添加哪个引用吗?如果你使用Windows窗体,它可以工作,但是如果你使用Xaml,它也可以工作吗?我从来没有尝试过绑定Xaml GUI的组件,但我认为现在使用它可能会更好。谢谢,我将尝试在我的应用程序中实现这一点。@Klyner您一定要研究数据绑定这是XAML最有用的功能之一。谢谢您的提示!顺便问一下:为了让下面的代码正常工作,你必须做些什么?PropertyChangedthis,新PropertyChangedEventArgsImageUri;c找不到方法您需要确保您的类实现INotifyPropertyChanged接口并添加属性已更改的事件处理程序…public event PropertyChangedEventHandler PropertyChanged;好的,我做了你告诉我的所有事情,但是现在当我尝试通过以下行更改图像时:ImageUri=new Urims-appx:///Assets/Minigame/kluis.jpg visual studio为我提供了一个NullReferenceException,该代码与您的代码非常相似。我是否必须将一些值更改为我在应用程序中使用的一些唯一的单词?当我将您的第一行添加到我的代码中时,我的内容屏幕变为黑色。@Klyner是imgCreatedFromMethod.Source null?
<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>