我正在向列表视图中添加一些文件。我想在鼠标双击时获取列表视图中项目的绝对路径。下面是我用来检索项目并将它们添加到列表视图的代码和 xaml
代码:
public class Documents
{
public string Name
{
get;
set;
}
public ImageSource Image
{
get;
set;
}
}
//Code to retrieve documents
String docpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] docnames = System.IO.Directory.GetFiles(docpath);
foreach (string docname1 in docnames)
{
System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(docname1);
string docname = Regex.Match(docname1, @".*\\([^\\]+$)").Groups[1].Value;
System.Windows.Controls.Image image = new System.Windows.Controls.Image();
int fileExtPos = docname.LastIndexOf(".");
if (fileExtPos >= 0)
docname = docname.Substring(0, fileExtPos);
FileInfo fileExt;
fileExt = new FileInfo(docname1);
if (fileExt.Extension.ToLower() == ".doc" || fileExt.Extension.ToLower() == ".docx" ||
fileExt.Extension.ToLower() == ".xls" || fileExt.Extension.ToLower() == ".xlsx" ||
fileExt.Extension.ToLower() == ".txt" || fileExt.Extension.ToLower() == ".rtf" ||
fileExt.Extension.ToLower() == ".pdf" || fileExt.Extension.ToLower() == ".dot" ||
fileExt.Extension.ToLower() == ".html" || fileExt.Extension.ToLower() == ".odt" ||
fileExt.Extension.ToLower() == ".odm" || fileExt.Extension.ToLower() == ".ott" ||
fileExt.Extension.ToLower() == ".info" || fileExt.Extension.ToLower() == ".xml" ||
fileExt.Extension.ToLower() == ".xps" || fileExt.Extension.ToLower() == ".xhtml" ||
fileExt.Extension.ToLower() == ".omm" || fileExt.Extension.ToLower() == ".csv")
{
files.Add(new Documents()
{
Name = docname,
Image = icon.ToImageSource()
});
}
}
XAML:
<GroupBox Grid.Column="1" Header="My Documents" HorizontalAlignment="Left" Margin="10,0,0,10" Width="200">
<ListView x:Name="DocsListView" HorizontalAlignment="Left" Height="500" VerticalAlignment="Top" Width="175" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.CanContentScroll="True" ItemsSource="{Binding docs, ElementName=MyWindow}" >
<ListView.View>
<GridView>
<GridViewColumn Header="File" Width=" auto">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Image Source="{Binding Image}" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Name" Width="auto" DisplayMemberBinding="{Binding Name}" />
</GridView>
</ListView.View>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<EventSetter Event="MouseDoubleClick" Handler="ListView_MouseDClick" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
</GroupBox>