ListView没有看到绑定对象属性

时间:2015-11-06 17:58:42

标签: c# xaml listview

我在显示外部类实例的属性时遇到问题。有ListView标记:

<ListView
x:Name="transportListView"
SelectionMode="None"
ItemsSource="{Binding MyModel}">
<ListView.ItemTemplate>
    <DataTemplate>
        <Border Padding="15" HorizontalAlignment="Center" Margin="0,0,0,10" Background="Gray">
            <StackPanel Margin="0,0,0,0">
                <TextBlock
                Text="{Binding ItemName}"
                Margin="0,0,0,0"/>
                <TextBlock
                Text="{Binding ItemCount}"
                Margin="0,0,0,0"/>
            </StackPanel>
        </Border>
    </DataTemplate>
</ListView.ItemTemplate>

MyModel是页面属性:

...
    public ObservableCollection<ExternalClass> MyModel { get; set; }
...

ExternalClass是某些引用库中的类:

namespace Library.Entities
{
    public class ExternalClass
    {
        public string ItemName { get; set; }
        public int ItemCount { get; set; }
    }
} 

因此,当我运行我的应用程序时,我会看到列表项,因为我设置了灰色,但ItemNameItemCount没有显示,为什么?我正确地将项目添加到集合中,并且绑定适用于内部类。

2 个答案:

答案 0 :(得分:2)

将您的ListView ItemsSource更改为ItemsSource="{Binding}"。像这样:

<ListView x:Name="transportListView" ItemsSource="{Binding}">
  ....

同样在this.DataContext = MyModel;下方添加InitializeComponent();后面的代码中:

public Window1()
{
    InitializeComponent();
    this.DataContext = MyModel;
}

答案 1 :(得分:0)

要使用ListView,您还需要为它定义视图(GridView):

    <ListView ItemsSource="{Binding MyModel}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="140" Header="Name" DisplayMemberBinding="{Binding ItemName}"/>
                    <GridViewColumn Width="140" Header="Count" DisplayMemberBinding="{Binding ItemCount}"  />
                </GridView>
            </ListView.View>
        </ListView>

如果要为每行定义模板,则可以使用ListBox而不是ListView:

<ListBox ItemsSource="{Binding MyModel}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Padding="15" HorizontalAlignment="Center" Margin="0,0,0,10" Background="Gray">
                        <StackPanel Margin="0,0,0,0">
                            <TextBlock Text="{Binding ItemName}" Margin="0,0,0,0"/>
                            <TextBlock Text="{Binding ItemCount}" Margin="0,0,0,0"/>
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>