0
这里是我的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" />
在上面案例我从我的数据库中获取所有组名称并作为组合框的项目正确显示。但这不是我想要的。我想在此组合框中显示两列。
案例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>
我没有得到在这种情况下任何错误,但我的组合框没有显示任何项目。
感谢您给出一个非常干净的答案,但我有一些您的答案出现问题。我完全按照你的回答,但现在我得到了所有项目中的管道符号(|)而不是文本。当我选择其中一个项目时,它会显示GroupAndEffect。 – Khushi
好吧,这些都是代码片段,我试图尽可能多地进入。这是一个非常好的教程,其中包含完整的工作代码,可以帮助您完成所有工作:http://code.msdn.microsoft.com/windowsdesktop/Best-ComboBox-Tutorial-5cc27f82#content – JnJnBoo
我发现问题但不知道如何解决它。我需要'覆盖'GroupAndEffect'类的ToString()'。我在下面提到的msdn aricle上发现它:http://msdn.microsoft.com/en-us/library/ms742521.aspx – Khushi