2008年11月30日日曜日

Silverlight+LINQでトランプ

岩永さんの「C#で大富豪」からパクったインスパイヤされた。



このコンテンツの再生にはSilverlight2が必要です。下の画像をクリックしてください。
Microsoft Silverlight を取得



ソースコードはここ。

練習を兼ねて、ListBoxにバインドしてみた。
Page.xamlはこう。

<UserControl x:Class="Millionaire.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Millionaire"
Width="108" Height="412"
Loaded="UserControl_Loaded">
<UserControl.Resources>
<my:CardImageConverter x:Key="cardImageConverter" />
<Style x:Key="CardPreview" TargetType="Image">
<Setter Property="Margin" Value="1,1,1,1"/>
<Setter Property="Width" Value="43"/>
<Setter Property="Height" Value="60"/>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="55"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListBox x:Name="CardList" Background="LightGray"
Grid.Row="0" Grid.Column="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Image
Source
="{Binding Converter={StaticResource cardImageConverter}}"
Style
="{StaticResource CardPreview}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="ShuffleButton" Grid.Row="0" Grid.Column="1"
Content="Shuffle" Click="ShuffleButton_Click" />
</Grid>
</UserControl>



型コンバーターはこう。

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Millionaire
{
public class CardImageConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (targetType != typeof(ImageSource))
return null;
Card c = value as Card;
if (c == null)
return null;
string name = (c.Suit == Suit.Joker)
? "joker"
: string.Format("{0}{1:00}", "cdhs"[(int)c.Suit], c.Number);
return new BitmapImage(
new Uri(string.Format("Images/{0}.png", name),
UriKind.Relative));
}

public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return null;
}
}
}



あとはバインドするだけ。

private void Shuffle()
{
Random random = new Random();
IEnumerable<Card> cards = Enumerable.Range(0, 53)
.OrderBy(x => random.Next())
.Select(x => new Card(x))
.Take(6)
.OrderBy(x => x.Rank)
.ThenBy(x => x.Suit);
CardList.ItemsSource = cards;
}

やってみて思ったけど、ListBoxそのままだと縦長だし複数選択はできないし、こりゃないわー。

0 件のコメント:

コメントを投稿