Wpf MVVM绑定列表<list <string>&gt;到datagrid </list <string>

时间:2014-10-12 09:58:27

标签: wpf binding

我希望模型的绑定属性到datagrid,我不能这样做 我有模特的财产 model包含带有字符串列表的列表 行计数在列表中是常量

public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class TestViewModel : ViewModelBase
    {
        public TestViewModel()
            : this(new FileService())
        {
        }

        public TestViewModel(IFileService fileService)
        {

            var list = new List<List<string>>();
            list.Add(new List<string>() { "1", "2", "3" });
            list.Add(new List<string>() { "3", "4", "5" });
            RecodListFromCsv = list;
        }

        private List<List<string>> _RecodListFromCsv;

        public List<List<string>> RecodListFromCsv
        {
            get { return _RecodListFromCsv; }
            set
            {
                if (_RecodListFromCsv != value)
                {
                    _RecodListFromCsv = value;
                    OnPropertyChanged("RecodListFromCsv");
                }
            }
        }
    }

XAML

<Window x:Class="Test.Views.TestView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewModel="clr-namespace:Test.ViewsModel"
        Title="PriceList" Height="427" Width="746">
    <Window.Resources>
        <viewModel:TestViewModelx:Key="TM" />
    </Window.Resources>    
    <DockPanel LastChildFill="True" DataContext="{Binding Source={StaticResource TM}}">
            <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding RecodListFromCsv}">
            </DataGrid>
        </Menu>
    </DockPanel>
</Window>

和UI显示 enter image description here

我做错了什么。怎么做?

1 个答案:

答案 0 :(得分:1)

datagrid的每个行项都是List<string>的类型,因此datagrid的自动生成列生成List<string>对象的公共属性(Capacity,Count)!.因此,如果您的商品编号为3,请使用List<List<string>>快速解决此问题而不是List<Tuple<string,string,string>>

var list = new List<Tuple<string,string,string>>();
list.Add(new Tuple<string,string,string>() { "1", "2", "3" });
list.Add(new Tuple<string,string,string>() { "3", "4", "5" });
RecodListFromCsv = list;

稳定的解决方案是创建一个持久化类并正确创建该对象类的列表。