如何绑定组合框的选定项目的ID而不是对象本身?

时间:2015-10-16 07:03:40

标签: c# entity-framework xaml data-binding combobox

考虑以下标记(最后三个标签仅用于开发目的,因此我可以验证绑定是否按照我的想法进行)。

<ComboBox x:Name="TimeFrame"
          DisplayMemberPath="Name"
          ItemsSource="{Binding TimeFrames}"
          SelectedItem="{Binding Path=Order.TimeFrame}"
          SelectionChanged="Combox_OnSelectionChanged" />
<Label Content="{Binding Path=Order.TimeFrame.Name}"></Label>
<Label Content="{Binding Path=Order.TimeFrame.Id}"></Label>
<Label Content="{Binding Path=Order.TimeFrameId}"></Label>

一切正常,更改的选项会更新到数据库并正确恢复。所有标签都按预期填充。有一点是错误的,即组合框中的选定项目未正确设置。由于我可以看到它绑定正确,我认为对象比较失败,因为订单中存储的是对象组合框但不是同一个实例的副本。

我在时间框架上使用部分类解决了它,如下所示。

public partial class TimeFrame
{
  public override bool Equals(object input)
  {
    TimeFrame comparee = input as TimeFrame;
    return comparee != null && comparee.Id == Id;
  }

  public override int GetHashCode()
  {
    return base.GetHashCode();
  }
}

果然,它有效,这进一步表明我的结论是正确的。现在我有两个问题。

  1. 有没有办法从标记中进行比较(即没有覆盖等式检查)?
  2. 我是否应该担心由于这些对象是不同的实例而导致比较失败(code smell风险)?

2 个答案:

答案 0 :(得分:0)

Selector及其后代不喜欢,非SelectedItem时非ItemsSource

假设您正在使用视图模型,最好在加载视图模型时将Order.TimeFrameTimeFrames同步。那就是:

if (Order.TimeFrame != null)
{
    Order.TimeFrame = TimeFrames.SingleOrDefault(_ => _.Id == Order.TimeFrame.Id);
}

Order.TimeFrame.Id不在TimeFrames ID中时,这也会正确处理案例。

答案 1 :(得分:0)

我认为你应该为SelectedTimeFrame添加一个属性并绑定它。

<ComboBox x:Name="TimeFrame"
      DisplayMemberPath="Name"
      ItemsSource="{Binding TimeFrames}"
      SelectedItem="{Binding Path=SelectedTimeFrame }"
      SelectionChanged="Combox_OnSelectionChanged" />

在属性设置器中更新Order.TimeFrame。