例如,我有这个课程
public class Task : DependencyObject
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string TaskName { get; set; }
public string Description { get; set; }
public DateTime BeginDate { get; set; }
public DateTime? Duration { get; set; }
public bool Done { get; set; }
}
我想将它保存在CheckBox实例上。是否可以将整个保存,或者至少可以放置一个int的属性?
我需要这个,因为当检查复选框时,我需要知道检查了哪个元素。
我如何生成UI:
private void pageLoaded(object sender, RoutedEventArgs e)
{
var obj = App.Current as App;
var query = obj.Connection.Table<Task>();
foreach (var task in query)
{
var stackLine = new StackPanel();
stackLine.Orientation = Orientation.Horizontal;
TextBlock taskName = new TextBlock();
taskName.Text = task.TaskName;
TextBlock taskDate = new TextBlock();
taskDate.Text = " " + task.BeginDate.ToString();
CheckBox taskDone = new CheckBox();
taskDone.Checked += new RoutedEventHandler(taskChecked);
if (task.Done == true)
taskDone.IsChecked = true;
stackLine.Children.Add(taskDone);
stackLine.Children.Add(taskName);
stackLine.Children.Add(taskDate);
listView.Items.Add(stackLine);
}
}
答案 0 :(得分:3)
你不应该浪费时间在C#中生成UI;你应该在XAML中编写它并编写一个viewmodel。你正在艰难地做事。从长远来看,我建议你学习使用XAML的所谓“正确方法”。它可以让你轻松地做很多很酷的事情和一些令人难以忍受的难以忍受的惊人事情。
但是你今天可能不会重写你的整个应用程序,你可以很容易地解决你的问题,如下所示。
创建CheckBox
时,将其Tag
属性设置为属于它的Task
对象:
CheckBox taskDone = new CheckBox();
taskDone.Checked += new RoutedEventHandler(taskChecked);
// Here:
taskDone.Tag = task;
在taskChecked
方法中:
private void taskChecked(object sender, RoutedEventArgs e)
{
var cb = (CheckBox)sender;
// Here we get the Task back from the Tag property.
// Tag is type Object, so we need to cast this one too.
var task = (Task)cb.Tag;
// Do stuff with the Task
task.Done = cb.IsChecked;
}