我已经尝试了几乎所有在stackoverflow上提供的资源,并且似乎无法让它发挥作用。我是wpf和mvvm的新手,并试图将数据表绑定到listview,下面是我的代码。
//code for viewmodel
public DataTable RetrieveDetails
{
get
{
DataTable users = new DataTable();
string dataBaseName = "name.db3";
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dataBaseName + "; Version=3;"))
{
var details = "SELECT * FROM users";
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(details, connection);
cmd.ExecuteNonQuery();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(details, connection);
adapter.SelectCommand.CommandTimeout = 120;
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}
}
}
下面是我如何将数据表绑定到列表视图
<ListView x:Name="FormOneView" ItemsSource="{Binding Path=RetrieveDetails}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding FirstName}" Header="First Name" />
</GridView>
</ListView.View>
</ListView>
我知道这应该很简单,但很难显示数据。
答案 0 :(得分:5)
尝试这种方法:
<ListView x:Name="FormOneView" ItemsSource="{Binding}" DataContext="{Binding Path=allData}" HorizontalAlignment="Left" Height="100" Margin="243,289,0,0" VerticalAlignment="Top" Width="191">
<ListView.View>
<GridView>
<GridViewColumn Header="Time" Width="50" DisplayMemberBinding="{Binding Path=Tid}"/>
<GridViewColumn Header="Acceleration" Width="70" DisplayMemberBinding="{Binding Path=Acceleration}"/>
</GridView>
</ListView.View>
</ListView>
在这个XAML中我给你一个带有两列的数据表的例子。我正在使用DisplayMemberBinding将ListView列绑定到我的sql表列标题。
您的backgournd代码实际上很好,但您需要使用propertyChangedEventHandler绑定ListView的DataContext。以下是如何进行此类绑定的示例:
在方法中添加以下两行:
adapter.Fill(ds, "users");
allData = ds.Tables["users"].DefaultView;
然后在您的课程中添加以下方法。您的类应继承INotifyPeropertyChanged (yourClassName:INotifyPeropertyChanged)否则它将无法正常工作。
private DataView _allData;
public DataView allData
{
get { return _allData; }
set
{
if (value != _allData)
{
_allData = value;
OnPropertyChanged("allData");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
结果:
答案 1 :(得分:0)
为了使上面的代码起作用,需要添加以下代码行 listview.datacontext =包含alldata.allData的类