我要做的只是让一个组合框填充来自sqlite表的数据。虽然我已经用代码方法做到了这一点,但我真的很想这样做,因为我看到的是更好的WPF做事情的方式。
据我所知,流程应该是这样的:
我应该有一个保存数据的类,我创建了一个快速类,默认构造函数是连接到数据库并将其结果转储到一个列表中,如下所示:
internal class mainmenusql
{
private List<string> _Jobs;
public mainmenusql()
{
SQLiteConnection conn = new SQLiteConnection();
conn.ConnectionString = "Data Source=C:\\Users\\user\\Documents\\db.sqlite;Version=3";
try
{
conn.Open();
SQLiteDataReader reader;
SQLiteCommand command = new SQLiteCommand(conn);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM Tasks";
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
_Jobs.Add(reader.GetValue(0).ToString());
}
}
else
{
MessageBox.Show("No records");
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
finally
{
conn.Close();
}
}
}列表"Object reference not set to an object instance“有一些错误。
但是不管怎样,下一步应该是将表单的DataContext设置为这个对象,对吗?
public MainWindow()
{
DataContext = new mainmenusql();
InitializeComponent();
}最后,combobox应该有一个绑定,对吗?
<Window x:Class="sqliteDatacontext.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox DataContext="{Binding Path=_Jobs}" HorizontalAlignment="Left" Margin="141,124,0,0" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>我在这里做错了什么?
发布于 2013-06-13 08:27:29
对于绑定到某种数据上下文,它需要通过公共getter /setter公开...
public class mainmenusql
{
public List<string> _Jobs
{ get ; protected set; }
public mainmenusql()
{
_Jobs = new List<string>();
// rest of populating your data
}
}窗口控件中的绑定是ItemsSource
<ComboBox ItemsSource="{Binding Path=_Jobs}" />"DataContext“应用于整个窗口...在此基础上,您的任何控件都可以将它们的元素“绑定”到数据上下文中几乎任何“公开”可用的元素上……在本例中,选项的ComboBox列表来自于它的"ItemSource“属性...所以你想让ITEMSOURCE指向你的_Jobs。
https://stackoverflow.com/questions/17077350
复制相似问题