C#ListView在WPF中,无法查看内容
本文关键字:WPF C#ListView | 更新日期: 2024-07-27 16:42:30
很快,我对网格和WPF还不熟悉,由于某种原因,我无法在ListView中看到我的内容,我很确定是网格造成的。
<Grid Canvas.Left="223" Canvas.Top="228">
<Grid.RowDefinitions>
<RowDefinition Height="9*"/>
<RowDefinition Height="28*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="8*"/>
<ColumnDefinition Width="21*"/>
<ColumnDefinition Width="29*"/>
<ColumnDefinition Width="29*"/>
</Grid.ColumnDefinitions>
<ListView HorizontalAlignment="Left" Height="123" VerticalAlignment="Top" Width="589" Name="LibraryList" Margin="-188,-76,-141.001,-10" IsEnabled="False" Grid.ColumnSpan="4" Grid.RowSpan="2" >
<ListView.View>
<GridView>
<GridViewColumn Header="Item Name" DisplayMemberBinding="{Binding ItemName}" Width="70"/>
<GridViewColumn Header="Copy Number" DisplayMemberBinding="{Binding CopyNumber}" Width="85"/>
<GridViewColumn Header="Guid" DisplayMemberBinding="{Binding Guid}" Width="100"/>
<GridViewColumn Header="Print Date" DisplayMemberBinding="{Binding Date}" Width="90"/>
<GridViewColumn Header="Best Seller" DisplayMemberBinding="{Binding BestSeller}" Width="90"/>
<GridViewColumn Header="Category" DisplayMemberBinding="{Binding Category}" Width="70"/>
<GridViewColumn Header="Sub Category" DisplayMemberBinding="{Binding SubCategory}" Width="80"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
实现是:
ManageCtors.InitJournal(int.Parse(copyNumber.Text), itemName.Text, DateTime.Parse(TimePrinted.Text), int.Parse(Guid.Text), (JournalCategory)Enum.Parse(typeof(JournalCategory), SubCategory.Text));
//Add to ListView
string[] row = { itemName.Text, copyNumber.Text, Guid.Text , TimePrinted .Text, Category.Text , SubCategory.Text = "None" };
ListViewItem _listViewItem = new ListViewItem();
_listViewItem.Content = row;
LibraryList.Items.Add(_listViewItem.Content);
有什么想法吗
BTW:有时我会收到一条消息:输入的格式不正确。
要绑定的数据是一个字符串数组,但在每个GridViewColumn中,都是按名称绑定的。这可能就是问题所在。
最好将数据行建模为其自己的类,并将该类的实例设置为ListViewItem.Content属性。
public class ItemData
{
public string ItemName { get; set; }
public int CopyNumber { get; set; }
public Guid Guid { get; set; }
public DateTime Date { get; set; }
public string BestSeller { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
}
ItemData row = new ItemData {
// set each property value
};
ListViewItem _listViewItem = new ListViewItem();
_listViewItem.Content = row;
LibraryList.Items.Add(_listViewItem.Content); // not sure if you need content here
我认为您最好将ItemsSource绑定到ListView上,而不是直接将项添加到ListView items集合中。
ObservableCollection<ItemData> items = new ObservableCollection<ItemData>();
// add your ItemData instances to the items collection
LibraryList.ItemsSource = items;
你最好还是遵循MVVM模式,在StackOverflow和其他地方有很多建议可以让你开始。