转换器未在WPF中显示的绑定图像

时间:2014-08-08 17:33:07

标签: c# wpf xaml imagesource

我试图让窗口显示一些扑克牌 - 只是一个带有'A' - 'K'的文本块和一个西装图片。我将这些图像存储在Resources.resx中Resources.SpadesResources.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,并且正在返回正确的图像资源(通过调试)。由于某种原因,图像只是没有显示。想法?

1 个答案:

答案 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;
}

现在一切正常。