0

我试图在列表框中显示文件的名称和路径。例如,名称应位于 Header FileName 下,路径应位于 FilePath 下。我不想绑定到任何 xml,因为我有一个代码来显示文件名和大小。我对此很陌生,我不知道该怎么做。谢谢!

4

2 回答 2

0

我不确定如何在没有看到您尝试绑定的任何代码或数据结构的情况下为您提供帮助,但我会试一试。

假设您正在尝试绑定 C:\MyFolder 目录中文件的名称和路径,并且您的网格视图有一个名称 grd_MyGrid:

string[] myFiles = Directory.GetFiles("C:\\MyFolder\\");

var files = from f in myFiles
                        select new{
                                    FileName =Path.GetFileName(f),
                                    FilePath = Path.GetPathRoot(f)
                                  };

grd_MyGrid.DataSource=files;

为了使其工作,您必须引用 System.Linq。

希望这可以帮助。

于 2011-08-26T06:07:55.633 回答
0

首先,我将提供一些代码,但是当涉及到 XAML 和 WPF 以用于未来的开发任务时,您确实应该至少阅读一些基础知识。

如果您可以不使用 ListBox,我建议您使用DataGrid(在 .Net 4.0 中 - 或在CodePlex 上的 WPF 工具包中)。在您希望在表格或报表中显示数据的情况下,DataGrid 更易于使用。

要在 XAML 中创建 DataGrid,可以使用以下代码(在 .net 4 中)

<DataGrid HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding Path=ItemsToDisplay}" IsReadOnly="True" AutoGenerateColumns="True" />

这将创建一个简单的DataGrid对象供您在屏幕上显示。因为AutoGenerateColumns已经设置为true,你的列将由控件自动为你创建。

您可能还注意到我已经设置了ItemsSource属性,这是 DataGrid 将从中获取项目的属性。

要在页面代码隐藏文件中定义它,您将能够执行以下操作:

public System.Collections.ObjectModel.ObservableCollection<Item> ItemsToDisplay { get; private set; }

请注意代码隐藏中的属性名称如何与 DataGrid 上的绑定中的属性名称相匹配。这就是 View(页面文件)链接到 ViewModel(代码隐藏)的方式

要对其进行测试,请创建一个简单的测试类并ItemsToDisplay使用项目填充集合。

例如:

在我的 MainWindow.xaml.cs 文件中

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ItemsToDisplay = new System.Collections.ObjectModel.ObservableCollection<Item>();

        ItemsToDisplay.Add(new Item("Homer", 45));
        ItemsToDisplay.Add(new Item("Marge", 42));
        ItemsToDisplay.Add(new Item("Bart", 10));
        ItemsToDisplay.Add(new Item("Lisa", 8));
        ItemsToDisplay.Add(new Item("Maggie", 2));
    }

    public System.Collections.ObjectModel.ObservableCollection<Item> ItemsToDisplay { get; private set; }
}

public class Item
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Item(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

在我的 MainWindow.xaml 文件中:

<Window x:Class="Stackoverflow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding Path=ItemsToDisplay}" AutoGenerateColumns="True" IsReadOnly="True" />
    </Grid>
</Window>

看起来像:

在此处输入图像描述

于 2011-08-26T06:10:22.557 回答