我想提前道歉,我不是WPF开发人员,我不知道所有的术语。
我有一个WPF应用程序,在其中,我有一个组合框。
在MainWindow.xaml.cs
文件中(我假设是View
的{{1}}部分?),我有一个类型为
MVVM
我想将组合框绑定到这本词典。
这是我到目前为止所尝试的:
public Dictionary<string, TeamData> Teams { get; }
问题是,即使这种绑定失败<ComboBox x:Name="TeamsDropdown" HorizontalAlignment="Left"
Margin="158,142,0,24" ItemsSource="{Binding Teams}" FontSize="18.667" Width="195"/>`
。我知道要将组合框项目中的文本作为所选字典项目的(there are no items in the dropdown)
,我必须使用key
或SelctedValue
...
但是我不知道哪个,在我开始工作之前我无法真正测试它。
SelectedValuePath
的构造函数:
MainWindow
答案 0 :(得分:1)
您需要将数据上下文设置为窗口。
DataContext = this;
此操作将刷新所有绑定。确保您之前(在示例中为Teams = TeamsData.Teams;
之后)正确加载了数据。
其他解决方案是使用observable partern和ObservableCollection以及INotifyProperty在修改数据时更新组合框。
这是最终ComboBox的最终结果:
<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>
答案 1 :(得分:0)
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); }}
xaml中的:
<ComboBox x:Name="PlayerName"
ItemsSource="{Binding Teams}"
DisplayMemberPath="Value.PlayerName"/>