简体   繁体   English

UWP Image.Source 与转换器绑定

[英]UWP Image.Source binding with converter

In my code I have a class with the following fields:在我的代码中,我有一个 class 具有以下字段:

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

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

Path property is there just for debugging.路径属性仅用于调试。

I also develop a converter in order to get rid of Path property.我还开发了一个转换器以摆脱 Path 属性。

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

When I use Path property as Image Source, everything works fine, but when I try to do the same with the SourceToImageConverter, app is not working.当我使用 Path 属性作为图像源时,一切正常,但是当我尝试对 SourceToImageConverter 执行相同操作时,应用程序无法正常工作。 I know converter is working as it Should cause when I use it on a TextBlock it shows the right value.我知道转换器正在工作,因为当我在 TextBlock 上使用它时,它会显示正确的值。 Xaml code looks like: 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"/>

Apply XamlBindingHelper.ConvertValue() to the value just as auto-generated {x:Bind} code is doing backstage.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