我正在尝试使用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>
提前致谢
最佳答案
创建一个viewmodel
,可以将其设置为XAML的数据上下文
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 节点中添加更新源触发器属性:
<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>