C# 将wpf组合框绑定到<;字符串,CustomClass>;,并使用自定义类的数据
我想提前道歉,我不是WPF开发人员,也不知道所有的术语 我有一个WPF应用程序,其中有一个组合框 在C# 将wpf组合框绑定到<;字符串,CustomClass>;,并使用自定义类的数据,c#,wpf,dictionary,combobox,binding,C#,Wpf,Dictionary,Combobox,Binding,我想提前道歉,我不是WPF开发人员,也不知道所有的术语 我有一个WPF应用程序,其中有一个组合框 在MainWindow.xaml.cs文件中(我假设它是MVVM?)的View部分),我有一个类型为 公共词典团队{get;} 我想把组合框绑定到这本字典上 这就是我迄今为止所尝试的: <ComboBox x:Name="TeamsDropdown" HorizontalAlignment="Left" Margin="158,142,0,24" ItemsSource="{Bind
MainWindow.xaml.cs
文件中(我假设它是MVVM
?)的View
部分),我有一个类型为
公共词典团队{get;}
我想把组合框绑定到这本字典上
这就是我迄今为止所尝试的:
<ComboBox x:Name="TeamsDropdown" HorizontalAlignment="Left"
Margin="158,142,0,24" ItemsSource="{Binding Teams}" FontSize="18.667" Width="195"/>`
您需要将数据上下文设置为窗口
DataContext = this;
此操作将刷新所有绑定。确保您的数据在之前(在示例中的Teams=TeamsData.Teams;
之后)正确加载
另一种解决方案是使用observable partern和observable Collection和INotifyProperty在修改数据时更新组合框
这是最终组合框的最终外观:
<ComboBox x:Name="TeamsDropdown" HorizontalAlignment="Left" Margin="158,142,0,24" FontSize="18.667" Width="195"
ItemsSource="{Binding Teams}"
SelectedValuePath="Key"
IsEditable="False">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="{Binding Value.Color, Converter={local:XnaColorToSolidColorBrushConverter}}" Width="16" Height="16" Margin="0,2,5,2" />
<TextBlock Text="{Binding Value.Name}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
这很简单。
给你的字典
我想你们班的团队是:
Public Class Teams
{
public String PlayerName { get; set; }
}
声明:
public static readonly DependencyProperty
TeamsProperty = DependencyProperty.Register("Teams", typeof(Dictionary<string, TeamData>), typeof(MainWindow), new PropertyMetadata(null));
public Dictionary<string, TeamData> Teams { get { return (Dictionary<string, TeamData>)GetValue(TeamsProperty); }}
公共静态只读从属属性
TeamsProperty=DependencyProperty.Register(“团队”、typeof(字典)、typeof(主窗口)、new PropertyMetadata(null));
公共词典团队{get{return(Dictionary)GetValue(TeamsProperty);}
在xaml中:
<ComboBox x:Name="PlayerName"
ItemsSource="{Binding Teams}"
DisplayMemberPath="Value.PlayerName"/>
试试这个:Teams.AsEnumerable().Select(x=>x.Key.ToArray();我相信一个更简单的方法是使用团队。Keys
,我也尝试过,但它仍然没有显示任何东西。我会在绑定时使用转换器,将字典转换为列表。在我的工作场所,有一个团队开发WPF,我总是看到他们在做什么。您完全可以将字典绑定到组合框。@GioraGuttsait在您的情况下,combobox
中的每个项都将是KeyValuePair
类型<代码>SelectedValue路径影响的是SelectedValue
,而不是显示内容。要更改用于显示的属性,请使用属性
<ComboBox x:Name="PlayerName"
ItemsSource="{Binding Teams}"
DisplayMemberPath="Value.PlayerName"/>