我正在尝试使用 WPF 和 C# 在 ListView
中显示数据,但我对看到的不同示例和方法感到困惑。我正在寻找一个与我的程序相似的完整工作示例,或使其工作的先决条件列表。如果我设法只显示我收藏中的一行数据,我会很高兴。目前, ListView 不显示任何内容。
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的code behind中,添加代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new WindowsViewModel();
}
}
在listview节点中添加update source trigger属性:
<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>
关于c# - 简单的 ListView 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003998/