我有一个Value Converter运行来自数据库的传入字符串值,以设置性别的相应图标。进入的值必须是M或F,其中任何一个将分别显示男性或女性图标。 Binding在某种程度上起作用,因为图片出现了,但它只显示了一组图标。
值转换器代码如下:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var gender = (string)value;
Uri uri;
uri = gender == "F" ?
new Uri("../Resources/Icons/female_user.png", UriKind.Relative) :
new Uri("../Resources/Icons/male_user.png", UriKind.Relative);
return uri;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
和XAML如下
<Image Margin="8" Width="35" Height="35"
VerticalAlignment="Top" HorizontalAlignment="Center"
Source="{Binding Gender, Converter={StaticResource genderConverter}}" />
资源在usercontrol.resources中引用,并且我假设所有资源都已正确绑定。那么为什么转换器只能持续返回一个值呢?
答案 0 :(得分:0)
试试这个......
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var gender = (string)value;
Uri uri;
uri = gender == "F" ?
new Uri("../Resources/Icons/female_user.png", UriKind.Relative) :
new Uri("../Resources/Icons/male_user.png", UriKind.Relative);
BitmapImage img_Gender = new BitmapImage(uri);
return img_Gender;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
答案 1 :(得分:0)
我需要的只是一个性别.Trim()来摆脱所有的空白区域。
var gender = value.ToString();
try
{
return gender.Trim() == "F" ? "../Resources/Icons/male_user.png" : "../Resources/Icons/female_user.png";
}
catch (Exception)
{
return "";
}
多数民众赞成这一切,它的确有效。谢谢你的回答和“doh!”尽管如此。