C# Wpf显示图像动态URI
我有一个自定义用户控件,它必须根据绑定到我的用户控件的属性值“动态”显示图像 范例C# Wpf显示图像动态URI,c#,wpf,C#,Wpf,我有一个自定义用户控件,它必须根据绑定到我的用户控件的属性值“动态”显示图像 范例 <Image Source="Resources/{0}.png" /> 图像的Source属性不完整:丢失的值{0}应以某种方式替换为我的模型值以检索图像 如何在wpf中实现这一点? 谢谢您可以通过向视图模型添加另一个属性来解决此问题 查看模型代码: private string _yourProperty; public string YourProperty
<Image Source="Resources/{0}.png" />
图像的Source属性不完整:丢失的值{0}应以某种方式替换为我的模型值以检索图像
如何在wpf中实现这一点?
谢谢您可以通过向视图模型添加另一个属性来解决此问题 查看模型代码:
private string _yourProperty;
public string YourProperty
{
get { return _yourProperty; }
set
{
if (_yourProperty == value) return;
_yourProperty = value;
OnPropertyChanged("YourProperty");
OnPropertyChanged("YourImageSource");
}
}
//this code is just for demo.
public BitmapImage YourImageSource
{
get
{
return new BitmapImage(BuildUriFromYourProperty());
}
}
Xaml代码:
<Image Source="{Binding YourImageSource}"/>
我使用值转换器解决:
public class ImageSelector : IValueConverter
{
public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
{
if( value == null )
return null;
string basePath = System.IO.Path.Combine( Directory.GetCurrentDirectory(), @"Resources\Devices" );
string imageName = String.Format( "{0}.png", value.ToString() );
string imageLocation = System.IO.Path.Combine( basePath, imageName );
if( !File.Exists( imageLocation ) )
imageLocation = System.IO.Path.Combine( basePath, "ImageUnavailable.png" );
return new BitmapImage( new Uri( imageLocation ) );
}
public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
{
throw new NotImplementedException();
}
}
XAML:
...
使用绑定转换器,它将通过WPF包Uri将您的属性转换为ImageSource。@克莱门斯,您能提供一个链接或代码段吗?我对wpf很陌生,一个例子对我很重要。为了作为绑定源,属性不必是依赖性属性。您的帖子没有回答这个问题,即如何从另一个视图模型属性创建ImageSource(或适当的URI)。@Clemens谢谢您的评论,我误解了这个问题。
<UserControl.Resources>
<local:ImageSelector x:Key="imageSelector"/>
</UserControl.Resources>
...
<Image Source="{Binding Converter={StaticResource imageSelector}}"/>