简单列表视图数据绑定
本文关键字:数据绑定 视图 列表 简单 | 更新日期: 2023-09-27 18:17:37
我正在尝试使用 WPF 和 C# 在ListView
中显示数据,我对我看到的不同示例和方法感到困惑。我正在寻找一个类似于我的程序的完整工作示例,或者使其工作的先决条件列表。如果我设法仅显示我收藏中的 1 行数据,我会很高兴。目前,列表视图不显示任何内容。
C#:
public partial class MainWindow : Window
{
public ObservableCollection<Row> Rows { get; set; }
public MainWindow()
{
InitializeComponent();
Rows = new ObservableCollection<Row>();
Rows.Add(new Row
{
ID = "42",
Category = "cat",
CharLimit = 32,
Text = "Bonjour"
});
}
}
public class Row
{
public string ID { get; set; }
public string Category { get; set; }
public int CharLimit { get; set; }
public string Text { get; set; }
}
XAML:
<ListView ItemsSource="{Binding Path=Rows}">
<ListView.View>
<GridView>
<GridViewColumn Width="200" Header="ID" DisplayMemberBinding="{Binding Path=ID}" />
<GridViewColumn Width="200" Header="Category" DisplayMemberBinding="{Binding Path=Category}" />
<GridViewColumn Width="200" Header="Text" DisplayMemberBinding="{Binding Path=Text}" />
</GridView>
</ListView.View>
</ListView>
提前致谢
创建一个可设置为 XAML 的数据上下文的viewmodel
public class WindowsViewModel
{
private ObservableCollection<RowViewModel> m_Rows;
public ObservableCollection<RowViewModel> Rows
{
get { return m_Rows; }
set { m_Rows = value; }
}
public WindowsViewModel()
{
Rows = new ObservableCollection<RowViewModel>();
Rows.Add(new RowViewModel
{
ID = "42",
Category = "cat",
CharLimit = 32,
Text = "Bonjour"
});
}
}
按以下方式实现类RowViewModel
:
public class RowViewModel:INotifyPropertyChanged
{
public RowViewModel()
{
}
private string m_ID;
public string ID
{
get
{
return m_ID;
}
set
{
m_ID = value;
NotifyPropertyChanged("ID");
}
}
public string Category
{
get;
set;
}
public int CharLimit
{
get;
set;
}
public string Text
{
get;
set;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string Obj)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this,new PropertyChangedEventArgs(Obj));
}
}
}
在 XAML 的代码隐藏中,添加以下代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new WindowsViewModel();
}
}
在列表视图节点中添加更新源触发器属性:
<ListView ItemsSource="{Binding Rows, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<ListView.View>
<GridView>
<GridViewColumn Width="200" Header="ID" DisplayMemberBinding="{Binding Path=ID}" />
<GridViewColumn Width="200" Header="Category" DisplayMemberBinding="{Binding Path=Category}" />
<GridViewColumn Width="200" Header="Text" DisplayMemberBinding="{Binding Path=Text}" />
</GridView>
</ListView.View>
否则,您必须指定 source,就像在您的情况下一样,它将在当前上下文中查找该属性,默认情况下,如果未指定任何其他内容,则该属性将DataContext
。尝试这样的事情:
<ListView ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=Rows}">
像这样,您指定它应该在当前Window
中查找Rows