将对象实例的属性从ObservableCollection绑定到ListView

时间:2016-11-10 19:22:21

标签: c# wpf listview data-binding datacontext

我需要将视图模型的ObservableCollection<T>属性绑定到视图。这是我的视图模型类。

namespace
{
    public class CompositeViewModel
    {
        public CompositeViewModel
        {
            IList<MyType> temp = new List<MyType>();
            for (int i = 0; i < 10; i++)
            {
                MyType entry = new MyType();
                entry.Id = 1;
                entry.Name = "Foo";
                temp.Add(entry);
            }

            CollectionB = new ObservableCollection<MyType>(temp);
        }

        public ObservableCollection<MyType> CollectionA
        {
            get;
            private set;
        }

        public ObservableCollection<MyType> CollectionB
        {
            get;
            private set;
        }
    }

    public class MyType
    {
        public string Name { get; set; }

        public int Id { get; set; }
    }
}

这是我的XAML用户控件。

<UserControl x:Class="Product.Views.CompositeView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:models="clr-namespace:Product.ViewModels"
             mc:Ignorable="d">
    <ListView ItemsSource="{Binding CollectionB}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Id" Width="300" DisplayMemberBinding="{Binding Id}"/>
                <GridViewColumn Header="Name" Width="300" DisplayMemberBinding="{Binding Name}"/>
            </GridView>
        </ListView.View>
    </ListView>

    <UserControl.DataContext>
        <models:CompositeViewModel/>
    </UserControl.DataContext>
</UserControl>

运行应用程序时,ListView会显示MyType类的完全限定名称。如何让它显示IdName字段的值?

编辑:添加了我看到的输出的屏幕截图。

enter image description here

由ABIN MATHEW编辑以显示我的输出。

enter image description here

1 个答案:

答案 0 :(得分:0)

我现在感到愚蠢。结果我在我的样式中声明了以下片段。

<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <ContentPresenter/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

另一个ListView实例需要它,我暂时将它放在app资源中。将其移动到实例自己的样式定义中可以解决问题。