我需要通过绑定将值从数据库传递到 Listview。我设法通过简单地将值添加到列表并将它们链接到所需的列来制作静态数据。但我不明白如何制作它以便我可以显示数据库中的值(我通过连接字符串和 MySQL 工作)。
标记是什么样的
<ListView
Name="LVBuild">
<ListView.View>
<GridView>
<GridViewColumn
DisplayMemberBinding="{Binding ID}"
Header="ID" />
<GridViewColumn
DisplayMemberBinding="{Binding Title}"
Header="Title" />
<GridViewColumn
DisplayMemberBinding="{Binding Description}"
Header="Description" />
<GridViewColumn
DisplayMemberBinding="{Binding BuildData}"
Header="BuildDate">
<GridViewColumn.CellTemplate>
我的模型
public class BuildModel
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string BuildData { get; set; }
public int Architect { get; set; }
public int Location { get; set; }
public int Teg { get; set; }
}
public class BuildManager
{
public static List<BuildModel> GetBuilds()
{
List<BuildModel> items = new List<BuildModel>();
items.Add(new BuildModel() {ID = 1, Title = "Test1", Description = "Desc1", BuildData = "12.12.2022", Architect = 1, Location = 1, Teg = 1});
items.Add(new BuildModel() {ID = 2, Title = "Test2", Description = "Desc2"});
items.Add(new BuildModel() {ID = 3, Title = "Test3"});
items.Add(new BuildModel() {ID = 4, Title = "Test4"});
return items;
}
}
如何传递模型的值
public partial class BuildPageAdmin : Page
{
private List<BuildModel> Builds;
public BuildPageAdmin()
{
InitializeComponent();
LVBuild.ItemsSource = BuildManager.GetBuilds();
}
}
简单地使用数据绑定:创建一个公共属性来保存源集合并使用数据库中的数据更新它。 数据绑定概述(WPF .NET)
如果您的收藏是
ObservableCollection
,您可以动态更新它:
<Page>
<ListView ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Page}, Path=Builds}">
</ListView>
</Page>
public partial class BuildPageAdmin : Page
{
// Create a binding source for the ListView
public ObservableCollection<BuildModel> Builds { get; }
public BuildPageAdmin()
{
InitializeComponent();
this.Builds = new ObservableCollection<BuildModel>();
this.Loaded += OnPageLoaded;
}
private void OnPageLoaded(object sender, RoutedEventArgs e)
=> UpdateBuildModels();
// Dynamically update the source collection at any time
private void UpdateBuildModels()
{
this.Builds.Clear();
// Get data from database
IEnumerable<BuldModel> newBuildModels = BuildManager.GetBuilds();
// Update source collection with new data from the database
foreach (BuildModel buildModel in newBuildModels)
{
this.Builds.Add(bulidModel);
}
}
}