【发布时间】:2016-10-18 20:58:22
【问题描述】:
我从 MySQL 数据库中获取结果,我想将它们显示在两列网格中。我已经在我的 MainWINdow.xaml 文件中设置了我的网格并添加了列定义。由于网格中的行数取决于数据库结果的数量,因此我在 c# 代码中定义了网格行。出于某种原因,grid.SetRow 和 grid.SetColumn 方法会抛出以下错误:
'System.Windows.Controls.Grid.SetRow(System.Windows.UIElement, int)' cannot be accessed with an instance reference; qualify it with a type name instead.
我不知道如何解决这个问题,因为我不知道“使用类型名称来限定它”是什么意思。我该如何解决这个问题?
这是我的 MainWindow.xaml.cs 文件:
MySqlConnection conn = new MySqlConnection(ConnString());
try
{
conn.Open();
string query = "SELECT * FROM maps ORDER BY MapTitle";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
RowDefinition MapRow = new RowDefinition();
int CurrentRow = 0;
int CurrentColumn = 0;
while (reader.Read())
{
/* Generate the preview attachment image */
Attachment PreviewFile = new Attachment();
PreviewFile.Details(Convert.ToInt32(reader["PreviewID"]));
BitmapImage MapPreview = new BitmapImage(new Uri(ImgURL() + "/" + PreviewFile.FileName, UriKind.Relative));
MapPreview.DecodePixelWidth = 384;
MapPreview.DecodePixelHeight = 216;
/* Generate the map title header */
TextBlock MapHeader = new TextBlock();
MapHeader.Text = Convert.ToString(reader["MapTitle"]);
BrushConverter bc = new BrushConverter(); //convert hex
MapHeader.Background = (Brush)bc.ConvertFrom("#243C5E");
MapHeader.Foreground = (Brush)bc.ConvertFrom("#F2F3F5");
/* If we're in the right column, set it to the left column for the next iteration */
if(CurrentColumn == 1){
CurrentColumn = 0;
CurrentRow++;
/* Otherwise, update which column we're in. */
} else {
CurrentColumn++;
MapRow = new RowDefinition();
}
MapGrid.RowDefinitions.Add(MapRow);
/* Add the map title header to the grid in the appropriate row and column. */
MapGrid.Children.Add(MapHeader);
MapGrid.SetRow(MapHeader, CurrentRow);
MapGrid.SetColumn(MapHeader, CurrentColumn);
/* Add the map preview image to the grid in the appropriate row and column. */
MapGrid.Children.Add(MapPreview);
MapGrid.SetRow(MapPreview, CurrentRow);
MapGrid.SetColumn(MapPreview, CurrentRow);
}
}
}
catch
{
MessageBoxResult result = MessageBox.Show("A database error occurred while gathering the results.");
}
finally
{
conn.Close();
conn.Dispose();
}
这是我的网格 XAML:
<Grid Name="MapGrid" HorizontalAlignment="Center" Margin="0,25,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".4*"/>
<ColumnDefinition Width=".4*"/>
</Grid.ColumnDefinitions>
</Grid>
感谢您的宝贵时间!
【问题讨论】:
-
改用 DataGrid 或 ListView。