1

在我的 ViewModel 中,我有一个可观察字符串集合的字典,声明如下。

public Dictionary<string, ObservableCollection<string>> NamePartsDict { get; set; }

我想在我的用户界面中将 Dictionary 绑定到 ComboBoxes,这样每个 ComboBox 都可以“选择”要绑定到的集合。

所以在我的 XAML 中,我想使用:

<ComboBox x:Name="comboBox" IsEditable="True"
    ItemsSource="{Binding CurrentLibrary.NamePartsDict[Year]}" Margin="80,0,0.871,0"></ComboBox>

我希望将其绑定到由键“Year”索引的集合,并使用存储在集合中的字符串填充组合框。

但是,此 XAML 会产生一个空的 ComboBox。

我已经验证可以绑定字典本身。下面的 XAML 使用每个键、值对的字符串表示形式填充组合框。

<ComboBox x:Name="comboBox" IsEditable="True"
    ItemsSource="{Binding CurrentLibrary.NamePartsDict}" Margin="80,0,0.871,0"></ComboBox>

从字典中获取值时,我的绑定路径中有什么错误吗?还是我正在尝试做一些不可能的事情(在这种情况下,我必须找到另一种方法!)?

非常感谢任何帮助!

蒂姆

4

2 回答 2

0

我通过使用转换器解决了这个问题:

/// <summary>
/// Returns a 
/// </summary>
public class DomainValueConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ObservableCollection<DomainValue> retVal = null;
        DomainDefinitionCollection dds = value as DomainDefinitionCollection;
        if (dds != null)
        {
            retVal = dds[parameter.ToString()];
        }
        return retVal;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

<controls:ComboBox VerticalAlignment="Center"
        DisplayMemberPath="Name"
        SelectedValuePath="Value"
        SelectedValue="{Binding ChildClientEntity.EditableEntity.EditableAttributes.TeamPosition, Mode=TwoWay}"
        ItemsSource="{Binding ChildClientEntity.Domains, Converter={StaticResource DomainValueConverter}, ConverterParameter=SiteVisitTeamPosition}" />

其中 ConverterParameter 是字典 Domains 的键。

public Dictionary<string, ObservableCollection<DomainValue>> Domains { get; private set; }
于 2013-04-11T20:15:12.827 回答
0

您应该在这里使用数据模板:http: //www.codeproject.com/Articles/47923/Using-a-different-DataTemple-when-a-WPF-ComboBox-i

于 2012-11-09T12:28:07.073 回答