我是C#和WPF的新手,我想制作一些类似电影库的数据库,其中MySQL作为数据库来使用Stackpanel显示图像和标题。
我不知道如何以编程方式在图像上添加click事件,因为我不在Xaml中使用该图像。
还可以让Stackpanel具有3x3或4x4网格,而不是只有1列吗?
我的程序的屏幕截图:
这是我的代码
public void FillData()
{
int id = 1;
for (int i = id; i < 100; i++)
{
MySqlCommand cmd;
cmd = koneksi.CreateCommand();
cmd.CommandText = "select * from movie_list where id_movie = '" + i + "'";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
if (ds.Tables[0].Rows.Count == 1)
{
string cover = (String)(ds.Tables[0].Rows[0]["cover"]);
string titles = (String)(ds.Tables[0].Rows[0]["title"]);
StackPanel Sp = sp;
StackPanel Sp2 = sp2;
Sp.Orientation = Orientation.Horizontal;
Sp2.Orientation = Orientation.Horizontal;
var picture = new Image
{
Name = "pb" + i,
Source = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + cover, UriKind.Absolute)),
RenderSize = new Size(100,150),
Margin = new Thickness(20,0,20,0),
};
var title = new Label
{
Name = "sp" +i,
Content = titles,
Width = 120,
Margin = new Thickness(10, 0, 20, 0),
HorizontalContentAlignment = HorizontalAlignment.Center,
};
Sp.Children.Add(picture);
Sp2.Children.Add(title);
}
}
}
答案 0 :(得分:2)
您确实应该将数据访问代码与UI代码分开。
在UI中,使用ItemsControl设置为DataSet的ItemsControl。使用每个项目所需的控件,将ItemsTemplate设置为DateTemplate。
使用列表框将处理项目选择,而不用担心图像和其他控件的单击事件。
如果要使用网格布局而不是直线列表,可以将UniformGrid用作ItemsPanelTemplate。
答案 1 :(得分:1)
您可以将事件处理程序添加到要创建的picture
对象中
picture.MouseUp += (s, e) => {
// Do something funny.
};
答案 2 :(得分:0)
除了您绝对不应该将数据库代码与UI代码混合之外,您还可以在Image上订阅MouseDown(或MouseUp,如果应该像单击一样)事件,然后执行您想要的任何东西:
picture.MouseDown += (sender, args) =>
{
Foo();
};
答案 3 :(得分:0)
var picture = new Image();
picture.MouseLeftButtonUp += (s, e) =>
{
//[your code goes here]
};