在做工控业界面时,运行时添加和编辑界面元素会给程序带来更大的灵活性,同时更能增加用户体验的好评度。
以下的例子代码实现:在应用程序界面需要更新时(如应用程序加载时)将存储于数据库的界面元素数据载入到UI当中,并且绑定一些事件或者菜单
前台代码:
<Canvas x:Name="AP_Plank" Height="3300" Width="2200"/>
后台代码:
/// <summary>
/// 将所有基站添加到系统界面当中
/// </summary>
void AddALlStationToUI()
{
BLL.Station SDB = new BLL.Station();
DataTable StationModelList = SDB.GetAll();
if (StationModelList.TableName != "正确")
{
//ConnectErorr("数据库连接错误:" + StationModelList.TableName);
//return 0;
}
if (StationModelList.Rows.Count < 1)
{
//ConnectErorr("数据库连接错误:从数据库未获取有效基站!");
//return 0;
}
for (int i = 0; i < StationModelList.Rows.Count; i++)
{
Station ap = new Station();
ap.IP = StationModelList.Rows[i]["IP"].ToString();
ap.ListenPort = Convert.ToInt16(StationModelList.Rows[i]["ListenPort"]);
ap.Coordinates_X = Convert.ToDouble(StationModelList.Rows[i]["Coordinates_X"]);
ap.Coordinates_Y = Convert.ToDouble(StationModelList.Rows[i]["Coordinates_Y"]);
ap.Coefficient_X = Convert.ToDouble(StationModelList.Rows[i]["Coefficient_X"]);
ap.Coefficient_Y = Convert.ToDouble(StationModelList.Rows[i]["Coefficient_Y"]);
ap.SN = StationModelList.Rows[i]["SN"].ToString();
ap.Remark = StationModelList.Rows[i]["Remark"].ToString();
ap.ID = new Guid(StationModelList.Rows[i]["ID"].ToString());
StationList.Add(ap);
UC.UC_AP UC_AP = new UC.UC_AP();
UC_AP.Tag = ap.ID;
System.Windows.Controls.ContextMenu contextmenu = new ContextMenu();
System.Windows.Controls.MenuItem MIViewStationInfor = new MenuItem();
MIViewStationInfor.Header = "查看详细信息";
MIViewStationInfor.Tag = ap.ID;
MIViewStationInfor.Click += new RoutedEventHandler(StationMenu_ViewStationInfor_Click);
contextmenu.Items.Add(MIViewStationInfor);
UC_AP.ContextMenu = contextmenu;
Canvas.SetTop(UC_AP, ap.Coordinates_Y);
Canvas.SetLeft(UC_AP, ap.Coordinates_X);
AP_Plank.Children.Add(UC_AP);
}
}
/// <summary>
/// 基站右键菜单(查看详细信息)事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void StationMenu_ViewStationInfor_Click(object sender, RoutedEventArgs e)
{
System.Windows.Controls.MenuItem MI = sender as System.Windows.Controls.MenuItem;
//此处可弹出窗口显示详细信息,同时可给窗口定义一个修改完成事件,当窗口修改完成时回刷主界面元素
MessageBox.Show(MI.Tag.ToString());
}