ListView数据绑定

时间:2013-01-10 19:07:32

标签: c# wpf xaml listview

我写的是简单WPF Application,我想使用ListView来显示List个项目。我的代码是:

WPF.xaml

<ListView Grid.Column="0" Grid.Row="1" Margin="10,0,10,5" ItemsSource="{Binding MyCollection.Elements}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding ElementDescriptions}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

WPF.xaml.cs

public MyViewModel ViewModel
    {
        get { return DataContext; }
        set { DataContext = value; }
    }

MyViewModel.cs

public OwnedCollection Elements { get; set; }

OwnedCollection.cs

public List<ElementDescriptions> ElementDescriptions { get; set; }

我100%肯定,ViewViewModel之间的通信是正确的,因为显示简单的消息并不会让我感到麻烦。我在ListView做了正确的约束吗?

1 个答案:

答案 0 :(得分:0)

一些事情:

首先,

TextBlock Text="{Binding ElementDescriptions}"

没有多大意义,因为ElementDescriptions是一个集合。如果你想遍历列表中的所有ElementDescriptions,你应该真正将ListView的ItemSource绑定到ElementDescriptions,然后访问ElementDescriptions类的一些text属性:

<ListView Grid.Column="0" Grid.Row="1" Margin="10,0,10,5" ItemsSource="{Binding MyCollection.ElementsElementDescriptions }">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ElementDescriptions.SomeTextField}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

其次,您使用的是INotifyPropertyChanged,以便视图知道更新吗?有关详细信息,请访问:OnPropertyChanged with a List