如何通过ObjectDataProvider将ComboBox绑定到通用字典 [英] How to bind a ComboBox to generic dictionary via ObjectDataProvider
本文介绍了如何通过ObjectDataProvider将ComboBox绑定到通用字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
XAML:
< Window x:Class =TestCombo234.Window1
xmlns =http://schemas.microsoft.com/winfx / 2006 / xaml / presentation
xmlns:x =http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local =clr-namespace:TestCombo234
Title =Window1Height =300Width =300>
< Window.Resources>
< ObjectDataProvider x:Key =ChoicesObjectType ={x:Type local:CollectionData}MethodName =GetChoices/>
< /Window.Resources>
< StackPanel HorizontalAlignment =Left>
< ComboBox ItemsSource ={Binding Source = {StaticResource Choices}}/>
< / StackPanel>
< / Window>
代码背后:
使用System.Windows;
使用System.Collections.Generic;
命名空间TestCombo234
{
public partial class Window1:Window
{
public Window1()
{
InitializeComponent() ;
}
}
public static class CollectionData
{
public static Dictionary< int,string> GetChoices()
{
字典< int,string> choices = new Dictionary< int,string>();
choices.Add(1,monthly);
choices.Add(2,quarterly);
choices.Add(3,每半年);
choices.Add(4,yearly);
返回选项;
}
}
}
但这给了我这个:
alt text http://img193.imageshack.us /img193/9218/choices.png
我需要更改什么,以便键是int,值是字符串?
解决方案
到您的ComboBox添加
SelectedValuePath =KeyDisplayMemberPath =Value
I want to fill a ComboBox with key/value data in code behind, I have this:
XAML:
<Window x:Class="TestCombo234.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestCombo234"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="Choices" ObjectType="{x:Type local:CollectionData}" MethodName="GetChoices"/>
</Window.Resources>
<StackPanel HorizontalAlignment="Left">
<ComboBox ItemsSource="{Binding Source={StaticResource Choices}}"/>
</StackPanel>
</Window>
Code Behind:
using System.Windows;
using System.Collections.Generic;
namespace TestCombo234
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
public static class CollectionData
{
public static Dictionary<int, string> GetChoices()
{
Dictionary<int, string> choices = new Dictionary<int, string>();
choices.Add(1, "monthly");
choices.Add(2, "quarterly");
choices.Add(3, "biannually");
choices.Add(4, "yearly");
return choices;
}
}
}
But this gives me this:
alt text http://img193.imageshack.us/img193/9218/choices.png
What do I have to change so that the key is the int and the value is the string?
解决方案
To your ComboBox add
SelectedValuePath="Key" DisplayMemberPath="Value"
这篇关于如何通过ObjectDataProvider将ComboBox绑定到通用字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文