简体   繁体   中英

WPF DataGrid shows length instead of path

I tried below code to retrieve directory name but it shows Length?

List<string> merchants = new List<string>();
foreach (string i in Directory.GetDirectories(Directory.GetCurrentDirectory() + "/Data/").ToList())
{
   merchants.Add(i);
}
merchantTable.ItemsSource = merchants;

result is

|Length|
_______________________
|20    |
|29    |

i tried below answers but same problem

How to get Directories name

Getting the folder name from a path

WPF Code

<DataGrid x:Name="merchantTable" HorizontalAlignment="Left" Margin="15,39,0,0" VerticalAlignment="Top" Width="208" Height="343"/>

Update

i use MessageBox it shows Returned values are Full path like C:\.....\Data\.....

A DataGrid is meant to show a set of columns, usually one for each property of the data item class, ie the element type of its ItemsSource collection.

Hence it doesn't make sense to use it for a collection of strings. Use a ListBox instead

<ListBox x:Name="merchantTable"/>

and simplify the ItemsSource assignment:

merchantTable.ItemsSource = Directory.GetDirectories(
     Path.Combine(Directory.GetCurrentDirectory(), "Data"));

If you really need to use a DataGrid, define a column like this:

<DataGrid x:Name="merchantTable" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Directory">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

This code makes nearly no sense; you call a method that returns an array of string, that you then convert to a list, that you then add one by one to another list..

Anyhow, I think you then did something like set DisplayMemberPath or BindingPath to @Length and now your list control is showing you the lengths of all the strings in the list - do a debug print of merchants[0] and it will be a string that is 20 characters long. Data binding typically only binds to properties and a string only has one property. If you want to bind to the string itself you'll probably need to bind the column to a path of .

If you're wanting to show a list of folder names you'll need to call

merchants.Add(Path.GetFileName(i.TrimEnd(Path.DirectorySeparatorChar)));

When GetFilename is used on a path like c:\temp\myfolder it returns MyFolder

the Trim() is there because if you call GetFilename on c:\temp\myfolder\ you get an empty string because it literally just returns everything after the last slash. (Which is nothing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM