这是我的ViewModel类
namespace ERP_Lite_Trial.ViewModels
{
public class GroupsViewModel : INotifyPropertyChanged
{
public GroupsViewModel()
{
using (DBEntities db = new DBEntities())
{
var groups = (from g in db.Groups
select g.Name).ToList();
this.GroupName = groups;
var correspondingEffects = (from g in db.Groups
select g.Type_Effect.Name).ToList();
this.EffectCorrespondingToGroup = correspondingEffects;
}
}
private List<string> _groupName;
public List<string> GroupName
{
get
{
return _groupName;
}
set
{
_groupName = value;
OnPropertyChanged("GroupName");
}
}
private List<string> _effectCorrespondingToGroup;
public List<string> EffectCorrespondingToGroup
{
get
{
return _effectCorrespondingToGroup;
}
set
{
_effectCorrespondingToGroup = value;
OnPropertyChanged("EffectCorrespondingToGroup");
}
}
public void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
现在我将向您展示两种情况:
案例1 :运作良好
<ComboBox x:Name="cbUnder" ItemsSource="{Binding Path=GroupName}" IsEditable="True"
Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="3" />
在上面的例子中,我从我的数据库中获取所有组名,并正确显示为comboBox的项目。但这不是我想要的。我想在这个组合框中显示两列。
案例2 :没有按预期工作(我可能会犯一些愚蠢的错误)
<ComboBox x:Name="cbUnder" IsEditable="True" Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="3">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=GroupName}" Width="100"/>
<TextBlock Text="|" Width="10" />
<TextBlock Text="{Binding Path=EffectCorrespondingToGroup}" Width="100"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
在这种情况下我没有收到任何错误,但我的组合框没有显示任何项目。
答案 0 :(得分:4)
您的代码需要在两个列表中创建您当前拥有的信息,因为它们在一个列表中彼此相关。作为两个单独的列表,没有办法将它们相互关联。
首先更改数据库查询,将信息作为对象列表返回。
using (DBEntities db = new DBEntities())
{
GroupsAndEffects = (from g in db.Groups
select new GroupAndEffect
{
GroupName = g.Name
EffectCorrespondingToGroup = g.Type_Effect.Name
}).ToList();
}
var组必须是对象列表,而不是字符串列表:
private List<GroupAndEffect> _groupAndEffects;
public List<GroupAndEffect> GroupsAndEffects
{
get
{
return _groupAndEffects;
}
set
{
_groupAndEffects = value;
OnPropertyChanged("GroupsAndEffects");
}
}
需要GroupAndEffect类
public class GroupAndEffect
{
public string GroupName;
public string EffectCorrespondingToGroup;
}
更新案例2:
<ComboBox x:Name="cbUnder" ItemsSource="{Binding GroupsAndEffects}" IsEditable="True" Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="3">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding GroupName}"/>
<TextBlock Text="|" Width="10" />
<TextBlock Text="{Binding EffectCorrespondingToGroup}" Grid.Column="1" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate></ComboBox>