簡體   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