我有两个这样的课程:
public class Instance
{
/// <summary>
/// Identity of index
/// </summary>
public int Id { get; set; }
/// <summary>
/// Items within this group.
/// </summary>
public Dictionary<string, ItemRow> Items;
public Instance()
{
//Items = new Dictionary<string, ItemRow>();
Items = new Dictionary<string, ItemRow>();
}
}
public class GroupMemory
{
/// <summary>
/// Name of the OPC group
/// </summary>
public string Name { get; set; }
/// <summary>
/// Scan rate for this group.
/// </summary>
public string ScanRate { get; set; }
/// <summary>
/// Number of instances for this group.
/// </summary>
public int CountOfInstances { get; set; }
/// <summary>
/// Instances within this group.
/// </summary>
public Dictionary<int, Instance> Instances;
/// <summary>
/// Items within this group.
/// </summary>
public Dictionary<string, ItemRow> Items;
/// <summary>
/// Constructor of GroupMemory class.
/// </summary>
public GroupMemory()
{
Items = new Dictionary<string, ItemRow>();
Instances = new Dictionary<int, Instance>();
}
}
我有一个listview,我在listview的每个项目中绑定GroupMemory对象。 listview的最后一列是一个ComboBox,我需要在其中绑定groupmemory的每个实例的Id。例如,如果每个组内存包含两个实例,并且实例具有Id = 1和Id = 2,我想在组合框中显示1和2作为其项目。我如何为组合框或其代码behinde编写xaml代码?
这是我的listview的xaml代码
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}, Converter={StaticResource starWidthConverter}}" DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn Header="Scan Rate" Width="60" DisplayMemberBinding="{Binding Path=ScanRate}" />
<GridViewColumn Header="Instances" Width="60" DisplayMemberBinding="{Binding Path=CountOfInstances}" />
<GridViewColumn Header="Index" Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox Width="50" ItemsSource="{Binding Instances}" SelectedValue="{Binding Id}" DisplayMemberPath="Id"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
答案 0 :(得分:3)
假设ComboBox的DataContext
是GroupMemory
类的实例,您可以尝试将ComboBox的ItemsSource
绑定到Instances.Values
属性并设置{{ 1}}显示每个DisplayMemberPath
的{{1}}:
Id
答案 1 :(得分:3)
您的Instances
被声明为字段,并且它不是有效的binding source。如果要绑定到属性,则应将其转换为属性。将声明更改为:
public Dictionary<int, Instance> Instances { get; set; }
然后,因为它是Dictionaty<K, V>
,并且每个项目都是KeyValuePair<K, V>
类型,其中Key
是int
而Value
是您的Instance
尝试将DisplayMemberPath
更改为Value.Id
<ComboBox ItemsSource="{Binding Instances}" DisplayMemberPath="Value.Id"/>
答案 2 :(得分:2)
如果将itemsource绑定到Instances属性,则可以将DisplayMember和/或valuemember绑定到Key或Value。
它相对简单
实例是KeyValuePair,您需要绑定到Value.Id
但是我也注意到你的类都没有实现INotifyPropertyChanged。您需要实现这一点,因为这是Binding知道您的值已更新的方式。
如果你仍然坚持使用字典,你可能还需要查看ObservableDictionary。 http://blogs.microsoft.co.il/shimmy/2010/12/26/observabledictionarylttkey-tvaluegt-c/