コンボボックスに 2 日以上取り組んでいますが、解決策が見つかりませんでした。
私の質問の 1 つで、JnJnBoo という名前のユーザーが私の質問に答えようとし、そこから知識とコードを取得しました。
MVVM パターンを使用して、複数の列のコンボボックスにデータを表示しようとしています。エンティティ フレームワークと SQL Server データベースを使用しています。
コードは次のとおりです。
namespace ERP_Lite_Trial.ViewModels
{
public class GroupsViewModel : INotifyPropertyChanged
{
public GroupsViewModel()
{
using (DBEntities db = new DBEntities())
{
GroupsAndCorrespondingEffects = (from g in db.Groups
select new GroupAndCorrespondingEffect
{
GroupName = g.Name,
CorrespondingEffect = g.Type_Effect.Name
}
).ToList();
EffectName = (from e in db.Type_Effect
select e.Name).ToList();
}
}
private List<GroupAndCorrespondingEffect> _groupsAndCorrespondingEffects;
public List<GroupAndCorrespondingEffect> GroupsAndCorrespondingEffects
{
get
{
return _groupsAndCorrespondingEffects;
}
set
{
_groupsAndCorrespondingEffects = value;
OnPropertyChanged("GroupsAndCorrespondingEffects");
}
}
private string _selectedGroup;
public string SelectedGroup
{
get
{
return _selectedGroup;
}
set
{
_selectedGroup = value;
OnPropertyChanged("SelectedGroup");
}
}
private List<string> _effectName;
public List<string> EffectName
{
get
{
return _effectName;
}
set
{
_effectName = value;
OnPropertyChanged("EffectName");
}
}
public void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class GroupAndCorrespondingEffect
{
public string GroupName;
public string CorrespondingEffect;
}
}
そして XAML :
<ComboBox x:Name="cbUnder" ItemsSource="{Binding Path=GroupsAndCorrespondingEffects}"
IsEditable="True" SelectedItem="{Binding Path=SelectedGroup, Mode=TwoWay}"
TextSearch.TextPath="GroupName" Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="3">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=GroupName}"/>
<TextBlock Text="{Binding Path=CorrespondingEffects}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
私は多くのことを試しましたが、常に失敗しました。
コンボボックスの項目にデータが表示されていませんが、コンボボックスで項目を選択すると、selectedGroup プロパティにデータが取得されます。データは namespace.classname です
したがって、GroupAndCorrespondingEffect クラスの Tostring メソッドをオーバーライドする必要があると思います。しかし、それには2つのプロパティがあります。XAML のデータ バインディングが想定するデータの形式は、私にはわかりません。では、tostring メソッドをオーバーライドするにはどうすればよいでしょうか。または、コードに何らかの間違いを犯している可能性がありますか?