在ListView中显示对象名称?

时间:2014-09-11 09:50:35

标签: c# wpf xaml

我想在listview中显示* .ps1文件名。

XAML:

  <ListView x:Name="script_pick"  Height="102" Loaded="Scripts_Loaded" ItemsSource="{Binding Name}"/>

我在我的方法中做得对吗?所有显示的都是listview中的WpfApplication2.Script,只有两个文件时有四个项目。

 private void Scripts_Loaded(object sender, RoutedEventArgs e)
        {

            var txtFiles = Directory.EnumerateFiles(Directory.GetCurrentDirectory() + @"\Scripts", "*.ps1");
            var scriptList = new List<Script>();

        foreach (string currentFile in txtFiles)
        {
            using (StreamReader sr = new StreamReader(currentFile, true))
            {
                script_pick.Items.Add(new Script { Name = System.IO.Path.GetFileName(currentFile),
                                                   ScriptCode = sr.ReadToEnd()});

                sr.Close();
            }

        }
    }

1 个答案:

答案 0 :(得分:0)

你应该将listView绑定到目标集合,我想这是script_pick.Items。

然后你有聪明的方法:为Script类添加一个datatemplate,以便xaml知道如何显示它。

或者您可以使用惰性(快速)方式:只需在Script类上覆盖ToString()以显示您想要的内容(Script.Name):)

顺便说一句,你不需要在使用块中关闭StreamReader。