我试图让窗口显示一些扑克牌 - 只是一个带有'A' - 'K'的文本块和一个西装图片。我将这些图像存储在Resources.resx中Resources.Spades
,Resources.Hearts
等等。
在我的Window.Resources xaml中,我有
<ResourceDictionary x:Name="HighCardsResources">
<c:SuitToImageConverter x:Key="SuitConverter" />
<DataTemplate x:Key="CardTemplate" DataType="{x:Type c:Card}">
<Border CornerRadius="10" Width="50" Height="50" BorderBrush="Black" BorderThickness="2">
<Grid Width="50" Height="50">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="18"/>
<ColumnDefinition Width="32"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding RankText}" Grid.Column="0" FontSize="24" />
<Image Source="{Binding Suit, Converter={StaticResource SuitConverter}}" Grid.Column="1" />
</Grid>
</Border>
</DataTemplate>
</ResourceDictionary>
我的SuitToImageConverter
代码是
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((Suit)value)
{
case Suit.Spades:
return Resources.Spades;
case Suit.Hearts:
return Resources.Hearts;
case Suit.Clubs:
return Resources.Clubs;
case Suit.Diamonds:
return Resources.Diamonds;
default:
return null;
}
}
我正在动态地将ContentPresenter
添加到网格中。
int col = 0;
foreach (Card card in hand.Cards)
{
DataTemplate template = FindResource("CardTemplate") as DataTemplate;
ContentPresenter cp = new ContentPresenter();
cp.ContentTemplate = template;
cp.SetValue(Grid.RowProperty, 0);
cp.SetValue(Grid.ColumnProperty, col);
cp.Width = 50;
cp.Height = 50;
cp.Content = card;
grdHand.Children.Add(cp);
col++;
}
我知道卡正确绑定,因为TextBlock获取了正确的字符串。我也知道正在使用SuitToImageConverter
,并且正在返回正确的图像资源(通过调试)。由于某种原因,图像只是没有显示。想法?
答案 0 :(得分:1)
我想通了这个link。 Resx图片的类型为Bitmap
,而Image.Source
则需要BitmapImage
类型。
我将SuitToImageConverter
更改为:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((Suit)value)
{
case Suit.Spades:
return ConvertToBitmapImage(Resources.Spades);
case Suit.Hearts:
return ConvertToBitmapImage(Resources.Hearts);
case Suit.Clubs:
return ConvertToBitmapImage(Resources.Clubs);
case Suit.Diamonds:
return ConvertToBitmapImage(Resources.Diamonds);
default:
return null;
}
}
private static BitmapImage ConvertToBitmapImage(Bitmap bitmap)
{
BitmapImage img = new BitmapImage();
img.BeginInit();
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Bmp);
stream.Seek(0, SeekOrigin.Begin);
img.StreamSource = stream;
img.EndInit();
return img;
}
现在一切正常。