【发布时间】:2021-07-12 04:44:31
【问题描述】:
我最近制作了一个由预先存在的表中的行组成的列表,并想尝试将该列表数据绑定到数据网格。然而,它只显示已定义的列名。有谁知道为什么这个绑定不起作用?
public class ViewModel1 : ViewModelBase, INotifyPropertyChanged
{
public List<Table1> AllDatainTable { get; set; }
private void SetInitialSettings()
{
AllDatainTable = new List<Table1>();
}
public List<Table1> GetAllDatainTable()
{
List<Table1> ret = new List<Table1>();
Table entity;
SqlDataAdapter da;
DataTable dt = new DataTable();
da = new SqlDataAdapter("SELECT * FROM Testdatabase.dbo.Table1", "Data Source=.;Initial Catalog=TestDatabase;Integrated Security=true");
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
entity = new Testdatarow();
entity.ID = Convert.ToInt32(dr["ID"]);
entity.Name = dr["Name"].ToString();
ret.Add(entity);
}
return ret;
}
还有xaml
<DataGrid Grid.Row="1" Grid.RowSpan="6" x:Name="ContDatagrid" CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding AllDatainTable, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="SizeToHeader" />
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="SizeToHeader"/>
</DataGrid.Columns>
</DataGrid>
还有数据模型本身
public class Table1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _ID;
public int ID
{
get { return _ID; }
set
{
_ID = value;
RaisePropertyChanged("ID");
}
}
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
RaisePropertyChanged("Name");
}
}
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
最后是它在一些早期测试中使用的连接字符串
<connectionStrings>
<add name="ConnectionToDb" connectionString="Data Source=.;Initial Catalog=Testdatabase;Integrated Security=true" providerName="System.Data.SqlClient" />
</connectionStrings>
【问题讨论】:
-
你真的打电话给
GetAllDatainTable()吗? -
需要额外的行或列?如果是列,则替换
AutoGenerateColumns="True"。 -
你设置了窗口的数据上下文了吗?例如,您可以在 xaml 中执行此操作:
<Window.DataContext><local:ViewModel/></Window.DataContext>
标签: c# sql wpf visual-studio entity-framework