【发布时间】:2014-01-27 22:37:21
【问题描述】:
我正在尝试使用 ValueConverter 设置图像的背景,当我直接在 XAML 中设置背景图像时它会显示,但使用转换器时它不会显示。
我用于创建按钮的 XAML 代码:
<Button x:Name="image" Grid.Column="2" VerticalAlignment="Center" Margin="0, 0, -1, 0" Width="100" Height="100" Click="image_CLick">
<Button.Background>
<ImageBrush ImageSource="{Binding Path=isSaved, Converter={StaticResource BoolImageConverter}}"/>
</Button.Background>
</Button>
isSaved 属性是用于确定要显示什么图像的布尔值。
这是我的 ValueConverter 代码,我尝试过使用 Uri 作为返回类型,但也已经尝试过 BitmapImage 或 String。但是 ImageSource(根据 MSDN)是一个 Uri。
public class BoolToImage : IValueConverter
{
public Uri TrueImage = new Uri("/Images/ThumbSelected@2x.png", UriKind.Relative);
public Uri FalseImage = new Uri("/Images/thumb.png", UriKind.Relative);
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is bool))
{
return this.FalseImage;
}
bool b = (bool)value;
if (b)
{
return this.TrueImage;
}
else
{
return this.FalseImage;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
如果我将返回类型更改为 BitmapImage,则此 ValueConverter 适用于普通 Image 元素。
有什么想法吗?
【问题讨论】:
-
我假设您已经尝试了显而易见的方法,例如从 Uri 路径中删除前导“/”并将“/”更改为“\”?
-
@TylerD87 Visual Studio 声明 '\' 是一个无法识别的转义序列。
-
将路径更改为@"Images\ThumbSelected@2x.png"。前面的 @ 符号告诉编译器忽略转义字符。或者,您可以将其写为“Images\\ThumbSelected@2x.png”
-
@TylerD87 太棒了!你可以把它作为答案,所以我可以接受。这是有效的答案。
-
干杯我已经做到了。
标签: c# silverlight xaml windows-phone-8 windows-phone