显然,上面代码的主体并没有更改—主要通过调用VisualTreeHelper类中的静态方法FindElementsInHostCoordinates来遍历Silverlight视觉树中的对象关系。但请注意,此处在从查询结果集中移除父结点后,判断条件更改为collidedElements.Count() >1。为什么呢?这是因为在我们把所有扑克控件添加到父控件Canvas中之前,我们提前在其中添加了几个Path和Rectangle控件。
此外,传递给方法GetPosition的参数不是cardContainer而是null),而传递给方法FindElementsInHostCoordinates的参数不是null而是cardContainer。
(7)定义新的扑克控件Card
在本游戏中,为了管理扑克的方便,我们也定义了一个独立的Silverlight用户控件—Card。这个控件类的总体实现逻辑与纸牌游戏中是一致的。显然,在本游戏中,我们只需要定义扑克的点数和花色即可,因为所有扑克都是正面向上的。
public partial class Card : UserControl
{
public int Number { get; set; }
public Suits CurrentSuit { get; set; }
private Uri[] uriPokerImages = {
new Uri("/SLFreeCell;Component/images/cards/cl1.PNG", UriKind.RelativeOrAbsolute),
new Uri("/SLFreeCell;Component/images/cards/cl2.PNG", UriKind.RelativeOrAbsolute),
//…omitted to save space
new Uri("/SLFreeCell;Component/images/cards/spk.PNG", UriKind.RelativeOrAbsolute)
};
//define an index pointer
public Uri this[int nIndex]
{
get
{
return uriPokerImages[nIndex];
}
set
{
uriPokerImages[nIndex]=value;
}
}
public Card(int number, Suits currSuit)
{
InitializeComponent();
this.Number = number;
this.CurrentSuit = currSuit;
this.imageHolder.Source = new BitmapImage(this[(int)currSuit * 13 + (number - 1)]);
}
}
{
public int Number { get; set; }
public Suits CurrentSuit { get; set; }
private Uri[] uriPokerImages = {
new Uri("/SLFreeCell;Component/images/cards/cl1.PNG", UriKind.RelativeOrAbsolute),
new Uri("/SLFreeCell;Component/images/cards/cl2.PNG", UriKind.RelativeOrAbsolute),
//…omitted to save space
new Uri("/SLFreeCell;Component/images/cards/spk.PNG", UriKind.RelativeOrAbsolute)
};
//define an index pointer
public Uri this[int nIndex]
{
get
{
return uriPokerImages[nIndex];
}
set
{
uriPokerImages[nIndex]=value;
}
}
public Card(int number, Suits currSuit)
{
InitializeComponent();
this.Number = number;
this.CurrentSuit = currSuit;
this.imageHolder.Source = new BitmapImage(this[(int)currSuit * 13 + (number - 1)]);
}
}
此外,我们只需定义除去大王和小王之外的52张图像,因为我们不再需要特殊的图像去担当占位符。总之,在本游戏中使用了一个简化版本的用户控件Card。