WPF编游戏系列 之四 用户控件

时间:2023-03-08 22:12:44
WPF编游戏系列 之四 用户控件

原文:WPF编游戏系列 之四 用户控件

       在上一篇《WPF编游戏系列 之三 物品清单》中,对物品清单进行了演示,其中反复用到了同一组控件(如下图),而且 颜昌钢也指出在3.2.2中使用的C#代码过多,其实我在写这些代码时也有同感,的确很繁琐也不好维护。其实这组控件的结构就是:<StackPanel><Image><Textblock><Textblock><Image>这5个控件的组合,那么能否将其做成一个控件组呢?“用户控件”即可实现这个功能。

WPF编游戏系列 之四 用户控件

1. 创建一个用户控件,右键项目名称,Add->New Item,选择User Control,新建一个GoodsElement控件。

WPF编游戏系列 之四 用户控件

VS会在Solution Explorer中创建一个新的XAML文件。

WPF编游戏系列 之四 用户控件

2. 控件创建好,就要对它进行编辑了,打开GoodsElement.xaml,将之前重复使用的控件全部定义到这里。

<UserControl x:Class="XMarket.GoodsElement"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="195" Width="150">
<Grid>
<Border BorderThickness="3" CornerRadius ="5"
Background="#FFFFCC" BorderBrush="#FF6633">
<StackPanel Orientation="Vertical" Margin="5"
HorizontalAlignment="Center">
<Image Name="goodsImage" Height="80" Width="80" Margin="5"></Image>
<TextBlock Name="goodsPrice" Margin="5"></TextBlock>
<TextBlock Name="goodsQty" Margin="5"></TextBlock>
<Image Name="goodsBuy" Source="image/add.png"
Height="25" Width="25" Cursor="Hand" Margin="5">
<Image.ToolTip>Add Quantity</Image.ToolTip>
</Image>
</StackPanel>
</Border>
</Grid>
</UserControl>

效果图:

WPF编游戏系列 之四 用户控件

3. 控件编好后,回到上一篇的3.2.2 将那些C#修改一下,代码行数减少了一半还多。这样做虽然C#少了,不知道程序的效率会不会提高?

int rowNum = 0;
int colNum = 0;
//Make element for goods
for (int i = 0; i < num; i++)
{
//使用刚定义的GoodsElement控件
GoodsElement goods = new GoodsElement();
BitmapImage bitImage = new BitmapImage();
bitImage.BeginInit();
bitImage.UriSource = new Uri("image/shop/" + res[i, 2].ToString(), UriKind.Relative);
bitImage.EndInit();
//直接在goods下就能找到相应的控件
goods.goodsImage.Source = bitImage;
goods.goodsPrice.Text = "Price: $" + res[i, 6].ToString();
goods.goodsQty.Text = "Quantity: " + res[i, 5].ToString(); goods.goodsQty.Name = "gQty" + res[i, 0].ToString();
object findTextObj = queryGrid.FindName("gQty" + res[i, 0].ToString());
if (findTextObj != null)
{
queryGrid.UnregisterName("gQty" + res[i, 0].ToString());
}
queryGrid.RegisterName(goods.goodsQty.Name, goods.goodsQty); goods.goodsBuy.Tag = res[i, 0].ToString() + "-" + res[i, 5].ToString() + "-" + res[i, 6].ToString();
goods.goodsBuy.MouseLeftButtonDown += addImage_MouseLeftButtonDown; goods.goodsBuy.Name = "bImage" + res[i, 0].ToString();
object findImageObj = queryGrid.FindName("bImage" + res[i, 0].ToString());
if (findImageObj != null)
{
queryGrid.UnregisterName("bImage" + res[i, 0].ToString());
}
queryGrid.RegisterName(goods.goodsBuy.Name, goods.goodsBuy); //Set GoodsElement grid postion
if (colNum == 5)
{
rowNum++;
colNum = 0;
}
goods.SetValue(Grid.RowProperty, rowNum);
goods.SetValue(Grid.ColumnProperty, colNum);
colNum++;
queryGrid.Children.Add(goods);
}

待续… …