简单的WPF ComboBox ItemsSource绑定不起作用

时间:2013-12-03 14:46:02

标签: .net wpf xaml combobox

我刚刚开始使用WPF和Visual Studio 2010。 当我尝试以下简单的ComboBox绑定时,我收到错误消息。

XAML:

...
<ComboBox Height="23" HorizontalAlignment="Left" 
Margin="33,18,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" 
ItemsSource="{Binding Path=test}"/>
...

代码文件:

public partial class SetupWindow2 : Window
{
    public List<string> test { get; set; }
    public SetupWindow2()
    {
        test = new List<string>() { "1", "2", "3" };
        InitializeComponent();
    }
}

错误讯息:

System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 40 : BindingExpression path error: 'test' property not found for 'object' because data item is null.  This could happen because the data provider has not produced any data yet. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 19 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')

这里的问题在哪里?

1 个答案:

答案 0 :(得分:3)

每当绑定失败时,您应首先检查DataContext,然后检查Binding表达式。

在你的情况下,我会说缺少正确的datacontext,所以如果你的组合框在你的setupwindow2中你应该添加:

public partial class SetupWindow2 : Window
{
   public List<string> test { get; set; }

   public SetupWindow2()
   {
      test = new List<string>() { "1", "2", "3" };
      this.Datacontext = this;
   }
}