[英]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.