我正在尝试创建一个允许您选择文件夹并在DataGrid上显示其文件信息的Lil工具。但是对于一个未知的原因,我不能将我的对象列表作为DataGrid的DataContext属性。
XAML代码:
<Window x:Class="WPFFileExplorer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFFileExplorer"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Background"
Value="Aqua" />
<Setter Property="FontSize"
Value="26" />
</Style>
</Window.Resources>
<Window.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF04B1CD"/>
<GradientStop Color="#FF66FB21" Offset="1"/>
</LinearGradientBrush>
</Window.Background>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60*"/>
<RowDefinition Height="201*"/>
<RowDefinition Height="58*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="76*"/>
<ColumnDefinition Width="182*"/>
<ColumnDefinition Width="182*"/>
<ColumnDefinition Width="77*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="File Explorer" Grid.Column="1" Grid.ColumnSpan="2" TextAlignment="Center" FontSize="42" FontFamily="Segoe UI Black" />
<DataGrid Name="fileslst" DataContext="{Binding}" Grid.Column="1" AutoGenerateColumns="False" Grid.ColumnSpan="2" Margin="30,0.441,30,0" Grid.Row="1">
</DataGrid>
</Grid>
C#代码:
namespace WPFFileExplorer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
List<Filei> files = new List<Filei>();
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileslst.DataContext = files;
DataGridTextColumn dgname = new DataGridTextColumn { Header = "Name"};
dgname.Binding = new System.Windows.Data.Binding("Name");
DataGridTextColumn dgpath = new DataGridTextColumn { Header = "Path" };
dgpath.Binding = new System.Windows.Data.Binding("Path");
DataGridTextColumn dgct = new DataGridTextColumn { Header = "Creation Time" };
dgct.Binding = new System.Windows.Data.Binding("CreationTime");
fileslst.Columns.Add(dgname);
fileslst.Columns.Add(dgpath);
fileslst.Columns.Add(dgct);
string[] filesarr = Directory.GetFiles(fbd.SelectedPath);
foreach (string s in filesarr)
{
FileInfo fi = new FileInfo(s);
DateTime ct = fi.CreationTime;
Filei f = new Filei() { Name = fi.Name, Root = s, CreationTime = ct };
}
}
}
}
public class Filei
{
public override string ToString()
{
return string.Format("Name: {0} \n Path: {1} \n Creation Time: {3}", Name, Root, CreationTime);
}
public string Name { get; set; }
public string Root { get; set; }
public DateTime CreationTime { get; set; }
}
}
非常感谢帮助者!