簡體   English   中英

UWP Image.Source 與轉換器綁定

[英]UWP Image.Source binding with converter

在我的代碼中,我有一個 class 具有以下字段:

public class Source
{
    public string Name { get; set; }
    ...

    public string Path { get => $"/Assets/Images/{Name}.svg"; }
}

路徑屬性僅用於調試。

我還開發了一個轉換器以擺脫 Path 屬性。

public class SourceToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return $"/Assets/Images/{value}.svg";
    }
}

當我使用 Path 屬性作為圖像源時,一切正常,但是當我嘗試對 SourceToImageConverter 執行相同操作時,應用程序無法正常工作。 我知道轉換器正在工作,因為當我在 TextBlock 上使用它時,它會顯示正確的值。 Xaml 代碼如下所示:

<Page.Resources>
    <local:SourceToImageConverter x:Key="SourceToImage"/>
    <DataTemplate x:Key="SourceListViewTemplate" x:DataType="models:Source">
        <StackPanel Orientation="Horizontal">
            <Image Source="{x:Bind Path}"/>
            <Image Source="{x:Bind Name, Converter={StaticResource SourceToImage}}"/>
            <TextBlock Text="{x:Bind Name, Converter={StaticResource SourceToImage}}"/>
        </StackPanel>
    </DataTemplate>
</Page.Resources>

...

<GridView
    x:Name="Source"
    ItemsSource="{x:Bind ViewModel.Sources}"
    ItemTemplate="{StaticResource SourceListViewTemplate}"
    IsItemClickEnabled="True"
    SelectionMode="Single"/>

XamlBindingHelper.ConvertValue()應用於值,就像自動生成的 {x:Bind} 代碼在后台執行一樣。

public class SourceToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        //if (targetType == typeof(string)) return $"/Assets/Images/{value}.svg";

        return XamlBindingHelper.ConvertValue(typeof(ImageSource), $"/Assets/Images/{value}.svg"); 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM