I have found several example of wpf combobox binding but when trying to adapt it I don't get the expected results. What appears in the combobox instead of the value is this: CuttingProblemHelper.Models.ComboBoxPairs
Can please anyone help?
Example of data in the SQL table:
Id CutProbCategId Problem
1 1 Brins coupés
2 1 Brins grafignés
3 1 Fil non dégainé
What I try to acheive is having a key, value pair for each entry in the combobox from an sql table.
So I created a class to store key, value pair:
namespace CuttingProblemHelper.Models {
public class ComboBoxPairs
{
public int _Key { get; set; }
public string _Value { get; set; }
public ComboBoxPairs(int _key, string _value)
{
_Key = _key;
_Value = _value;
}
} }
Next get the data from the table and add them to the object ComboBoxPairs
private void AddProblemCategtoCombobox(int categ)
{
// erase list
cmbxProblem.ItemsSource = null;
// get list
DataRow[] CutProblemsRows = gediDataSet.CutProblems.Select("CutProbCategId= " + categ);
// we have rows
if (CutProblemsRows != null)
{
// initialize object ComboBoxPairs
List<ComboBoxPairs> cbp = new List<ComboBoxPairs>();
foreach (DataRow row in CutProblemsRows)
{
// add id and problem key, value pair
cbp.Add(new ComboBoxPairs(int.Parse(row["Id"].ToString()), row["Problem"].ToString()));
}
// define properties of combobox
cmbxProblem.DisplayMemberPath = "_Value";
cmbxProblem.SelectedValuePath = "_Key";
// bind comboboxpairs list
cmbxProblem.ItemsSource = cbp.ToList();
}
}
Here's the XAML of the combobox and formatting of the display of items:
<ComboBox x:Name="cmbxProblem" Grid.Column="1" Margin="10,10,10,10" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" SelectionChanged="cmbxProblem_SelectionChanged" FontSize="40" ItemsSource="{Binding Collection}" Grid.ColumnSpan="2">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBoxItem}">
<Label Name="lbl" Content="{Binding}" ></Label>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="lbl" Property="FontStyle" Value="Normal"></Setter>
<Setter TargetName="lbl" Property="Background" Value="AliceBlue"></Setter>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="lbl" Property="FontStyle" Value="Italic"></Setter>
</Trigger>
<Trigger Property="IsSelected" Value="False">
<Setter TargetName="lbl" Property="FontStyle" Value="Normal"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
Thank you very much!