2012-10-20 53 views
0

我用下面的代码:如何绑定一个ComboBox通用字典使用XAML代码

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 ?!

+0

您需要将您的窗口的DataContext设置为数据绑定工作的实例。你可以在'this.DataContext = this;'的构造函数中做到这一点,因为你在本地绑定窗口。你应该在数据绑定时检查你的输出窗口,你可以看到为什么数据绑定失败的一些小细节。 –

回答

1

您的房产被标记为private,使其成为public。另外,请将您的ComboBox上的外壳更正为ValueKey。第三,你的绑定表达式看起来无效,请仔细检查。最后,它看起来像你的属性是视图的代码隐藏文件的一部分。你可能会考虑MVVM设计模式。

更新

Window有 'eportslettra' 的Name,但你的绑定表达式使用ElementName 'reportslettra'。纠正其中一个。

+0

我用:public Dictionary GetNumber {get;组; }。但不在组合框中显示数据。为什么? –

+0

答复已更新。 – devdigital

+0

问题已更新。请检查。 –

相关问题