ListView无法正确绑定使用

时间:2015-01-05 19:45:43

标签: c# wpf listview binding

我一直在翻阅其他人'关于这个主题的问题和答复一整天都没有,但似乎没有任何效果。我试图将一个空的ObservableCollection绑定到一个ListView,该ListView将在用户添加数据时填充。从我在输出窗口中可以看出,DataContext没有显示我创建的公共变量以绑定到ListView。我仍然是WPF的新手,所以很可能我错过了一些东西,但我只是没有看到它。

XAML:

<ListView Grid.Row="0" Grid.ColumnSpan="5" HorizontalAlignment="Stretch" 
      ItemsSource="{Binding Path=fieldAnalysis}" 
      Name="listviewFieldAnalysis">                                          
<ListView.View>
....

CS:

public partial class MainWindow : Window
{
    public ObservableCollection<FieldSample> fieldAnalysis;
    public MainWindow()
    {
        InitializeComponent();
        fieldAnalysis = new ObservableCollection<FieldSample>();
        this.DataContext = this;
    }
...

输出窗口:

System.Windows.Data Error: 40 : BindingExpression path error: 'fieldAnalysis' property not found on 'object' ''MainWindow' (Name='')'. BindingExpression:Path=fieldAnalysis; DataItem='MainWindow' (Name=''); target element is 'ListView' (Name='listviewFieldAnalysis'); target property is 'ItemsSource' (type 'IEnumerable')

我已经阅读了错误消息的细分,但我仍然不确定为什么XAML无法访问&#39; fieldAnalysis&#39;变量。任何帮助是极大的赞赏。提前谢谢。

3 个答案:

答案 0 :(得分:0)

你的课应该是这样的:

  public partial class MainWindow : Window, INotifyPropertyChanged
  {
   private ObservableCollection<FieldSample>_fieldAnalysis;
   public ObservableCollection<FieldSample> fieldAnalysis
   {
    get{return _fieldAnalysis;}
    set{
        _fieldAnalysis=value;
        if (PropertyChanged != null)
            {
             PropertyChanged(this,new PropertyChangedEventArgs("fieldAnalysis"));
            }
       }
   }

   public event PropertyChangedEventHandler  PropertyChanged;

public MainWindow()
{
    InitializeComponent();
    fieldAnalysis = new ObservableCollection<FieldSample>();
    this.DataContext = this;
}

如果未在Window上实现INotifyPropertyChanged,则必须在调用InitializeComponent之前实例化Observable集合

public partial class MainWindow : Window
{
public ObservableCollection<FieldSample> fieldAnalysis;
public MainWindow()
{
    fieldAnalysis = new ObservableCollection<FieldSample>();
    InitializeComponent();
    this.DataContext = this;
}

答案 1 :(得分:0)

如何添加''到

 ItemsSource="{Binding Path=fieldAnalysis}" 

 ItemsSource="{Binding Path='fieldAnalysis'}" 

不确定,但我认为这会有所帮助

答案 2 :(得分:0)

您需要创建一个属性并绑定到该属性。

E.g。在您的viewmodel中:

public ObservableCollection<FieldSample> FieldAnalysis {
   get {
      return fieldAnalysis;
   }
}

然后在你看来:

ItemsSource="{Binding FieldAnalysis}"