How come my databinding is writing out the Length

2019-02-28 08:43发布

So I've setup a viewmodel to where it binds an ObservableCollection<string> to my DataGrid.

It prints out the value just fine but it also prints out the Length of the property? I don't recall ever setting that in any binding whatsoever. Why is it doing that?

Visual representation of what it looks like

My MainWindow.cs

public MainWindow()
{
    InitializeComponent();
    DataContext = new MasterViewModel();
}

MasterViewModel.cs

class MasterViewModel
{
    public Users Users { get; } = new Users();
    public Achievements Achievements { get; } = new Achievements();
}

Users.cs

class Users : INotifyPropertyChanged
{
    public Users()
    {
        newList.Add("Hello there");
    }

    private ObservableCollection<string> newList = new ObservableCollection<string>();

    public ObservableCollection<string> NewList
    {
        get { return newList; }
        set { newList = value; }
    }


    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML

<DataGrid ItemsSource="{Binding Users.NewList}" Width="400" Height="200" Margin="182,158,210,61">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"></TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

2条回答
beautiful°
2楼-- · 2019-02-28 08:54

I forgot to add the property AutoGenerateColumns="False". Not sure why it was set to true by default or why it woudl choose the length property of all the properties but I guess I got it fixed.

查看更多
姐就是有狂的资本
3楼-- · 2019-02-28 09:07

DataGrid has property AutoGenerateColumns which is set to True by default and makes DataGrid to create a column for each property defined in items.

DataGrid is bound to NewList which contains items of type string which has Length property. So it makes Length column

you can disable auto-generation by setting <DataGrid AutoGenerateColumns="False" ...

查看更多
登录 后发表回答