我一直在尝试像下面的屏幕截图那样复制Listview
但是我的问题是我无法使其正常工作。我对MVVM很陌生
这是我的xaml代码
<ListView Margin="10,10,10,6" x:Name="BusinessListView">
<ListView.View>
<GridView>
<GridViewColumn Header="Company" DisplayMemberBinding="{Binding Company}" />
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" Text="{Binding BusinessType}"></TextBlock>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
下面是我的视图模型代码
List<BusinessM> businesses = new List<BusinessM>();
businesses.Add(new BusinessM
{
BusinessType = "Enterprise",
ListBusiness = new List<BusinessInfo>
{
new BusinessInfo {Company = "Microsoft"}
}
});
BusinessListView.ItemsSource = businesses;
型号
public class BusinessM
{
public string BusinessType { get; set; }
public List<BusinessInfo> ListBusiness { get; set; }
public BusinessM()
{
ListBusiness = new List<BusinessInfo>();
}
}
public class BusinessInfo
{
public string Company { get; set; }
}
当我运行程序时,它返回错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'Company' property not found
我的代码有什么问题?我了解到我没有正确地将物业公司引用到Listview中?
是这样的。我该怎么做。我一直在尝试自己解决问题,但无法使其正常工作。
谢谢。
答案 0 :(得分:0)
由于数据结构绑定到listview的item source属性的方式,您将收到指定的错误。通常,您将有一个扁平化的模型列表,然后使用ColllectionViewSource
对集合应用分组和/或排序。
在发布的代码中,您将ItemSource绑定到BusinessM
的列表,这意味着每个列表视图项目都代表类型BusinessM
的对象。因此,当您将GridViewColumn
绑定到Company
时,它期望BusinessM
类型具有名称相似的属性,顺便说一句,情况并非如此。
我已经修改了您的代码,以便可以通过示例向您解释(IMO)。
型号:
public class BusinessM
{
public string BusinessType { get; set; }
public string Company { get; set; }
}
(xaml.cs)后面的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CollectionViewSource cvs = new CollectionViewSource();
cvs.Source = GenerateData();
cvs.GroupDescriptions.Add(new PropertyGroupDescription(nameof(BusinessM.BusinessType)));
BusinessListView.ItemsSource = cvs.View;
}
private List<BusinessM> GenerateData()
{
List<BusinessM> businesses = new List<BusinessM>();
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 5; j++)
{
businesses.Add(new BusinessM
{
BusinessType = $"Type {i}",
Company = $"{i}{j}"
});
}
};
return businesses;
}
}
查看(xaml):
<ListView Margin="10,10,10,6" x:Name="BusinessListView">
<ListView.View>
<GridView>
<GridViewColumn Header="" Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Company" DisplayMemberBinding="{Binding Company}" />
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Expander IsExpanded="True" Header="{Binding Name}">
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
</ListView>