如何使用XAML代码将Combobox与通用词典结合



我正在使用以下代码:

private Dictionary<string, string> GetNumber { get; set; }
public ReportsLetterTra()
{
    GetNumber = new Dictionary<string, string>
                            {
                                {"1", "First"},
                                {"2", "Second"}
                            };
    InitializeComponent();
}

XAML代码:

 <ComboBox 
      DisplayMemberPath="value" 
      SelectedValuePath="key" 
      ItemsSource="{Binding ElementName=reportslettra,Path=GetNumber}"
      SelectedIndex="0" Name="cmbFromNumber" />

为什么不将getnumber绑定到cmbfromnumber?!

更新:

我的完整代码在后面的文件中:

using System.Collections.Generic;
using System.Windows;
namespace WpfApplication20
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Dictionary<string, string> GetNumber { get; set; }
        public Window1()
        {
            GetNumber = new Dictionary<string, string>
                                    {
                                        {"1", "First"},
                                        {"2", "Second"}
                                    };
            InitializeComponent();
        }
    }
}

我的完整XAML代码:

<Window x:Class="WpfApplication20.Window1" Name="eportslettra"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid Height="26">
        <ComboBox DisplayMemberPath="Value" SelectedValuePath="Key" 
               ItemsSource="{Binding ElementName=reportslettra,Path=GetNumber}" 
               SelectedIndex="0"  Name="cmbFromNumber"    />
    </Grid>
</Window>

我的错是在哪里?为什么不将getnumber绑定到cmbfromnumber?!

您的属性被标记为private,使其成为public。另外,将ComboBox上的套管更正为ValueKey。第三,您的绑定表达式看起来无效,请仔细检查一下。最后,看来您的属性是View代码后面的属性的一部分。您可以考虑MVVM设计模式。

update

您的Window具有'eportslettra'的Name,但是您的绑定表达式使用ElementName" ReportsLettra"。纠正其中之一。

最新更新