【发布时间】:2022-01-22 10:28:55
【问题描述】:
我找到了几个 wpf 组合框绑定的示例,但是在尝试调整它时,我没有得到预期的结果。出现在组合框中而不是值的是: CutProblemHelper.Models.ComboBoxPairs
可以请任何人帮忙吗?
SQL表中的数据示例:
Id CutProbCategId 问题
1 1 布林斯双门轿车
2 1 布林斯涂鸦
3 1 Fil non dégainé
我试图实现的是为来自 sql 表的组合框中的每个条目提供一个键值对。
所以我创建了一个类来存储键值对:
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;
}
} }
接下来从表中获取数据并将它们添加到对象 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();
}
}
这是组合框的 XAML 和项目显示的格式:
<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>
非常感谢!
【问题讨论】:
-
stackoverflow.com/questions/70309478/… 还有这个:
cmbxProblem.ItemsSource = cbp.ToList();应该是:cmbxProblem.ItemsSource = cbp; -
试试DisplayMemberPath 属性
-
cmbxProblem.ItemsSource = cbp;不起作用。
-
DisplayMemberPath 已添加,但它没有单独执行任何操作。也许还缺少其他东西。我放弃了使用类来存储键值对的想法,而是使用了它: MyCollection = new ObservableCollection
>();但是我仍然需要帮助才能仅将值显示为组合框中的项目,而不是现在的 [Key, Value]。我还不知道如何解决这个问题。