【问题标题】:XAML Binding Value from other Collection来自其他集合的 XAML 绑定值
【发布时间】:2012-03-03 20:12:11
【问题描述】:

我真的在网上搜索过,没有找到答案。

我很难描述我想要做什么。也许这就是我的原因 在 Stackoverflow 和 Google 上找不到答案。

我的页面中有一个ListBox,它绑定到ObservableCollection<Model>。 此Model 的属性具有另一个模型的Id。还有 一个Dictionary<int,SecondModel>,包含真正的第二个模型。

我可以将第二个模型的属性添加到第一个模型,因为这是第三方库。

是否可以使用集合从已分配的SecondModel 中获取Name 属性?

Text="{Binding ???}"

样本

public class Model
{
    public int Id { get; set; }
    public int SecondModelId { get; set; }
}

public class SecondModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class SomeOtherModel
{
    public Dictionary<int,SecondModel> SecondModelCollection{ get; set; }
}

【问题讨论】:

  • 这很令人困惑 :) 但是你说 ListBox in my Page 绑定到 ObservableCollection 然后你问 是否可以获得模型来自集合?因为原样,你正在使用Model
  • ;) 我的意思是我想获得 SecondModel 但我只有 id。提前致谢!
  • 所以使用ObservableCollection&lt;Model&gt;作为数据源,例如你想得到Name。我做对了吗?
  • 是的,我有ObservableCollection&lt;Model&gt;Model 具有 SecondModel 的 id ...我需要 SecondModelName 属性。

标签: silverlight xaml data-binding


【解决方案1】:

如果你不能玩Model 类的胆量,我建议将这两个模型包装在类似的东西中:

public class JoinedModel
{
  public Model FirstModel{ get; set; }
  public Model SecondModel{ get; set; }
}

 var secondModelCollection = SomeOtherModel.SecondModelCollection.Values;

 var joinedCollection = from model in firstModelCollection
                              join secondModel in secondModelCollection 
                              on model.SecondModelId equals secondModel.Id
                              select new JoinedModel() { FirstModel = model, SecondModel = secondModel };

您可以将joinedCollection 设置为数据源,而不是问题中以ObservableCollection&lt;Model&gt; 给出的firstModelCollection

然后在绑定中,你可以像Text="{Binding SecondModel.Name}"那样做一个两级绑定

...寿,我假设您可以更改视图的数据源,希望您可以:)

【讨论】:

    【解决方案2】:

    我喜欢 zortkun 的解决方案。您还可以使用 IValueConverter

    <UserControl.Resources>
      <my:SecondValueConverter x:Name="SecondValueLookup" />
    </UserControl.Resources>
      :
      :
    <TextBlock Text="{Binding SecondValueId, 
                      Converter={StaticResource SecondValueLookup}, 
                      ConverterParameter=Name}" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多