在MouseDoubleClick事件上从ListView打开文件

时间:2012-03-28 10:23:14

标签: c# wpf xaml listview mouseevent

我正在尝试创建一个Windows资源管理器。 我已经成功填充了treeView和listView,就像windows explorer一样,但是我在从listView双击打开文件时遇到了问题。

这是我到目前为止所做的:

try
        {
            //clears the collection so the listview has only the files of the folder thats clicked on
            _fileDetails.Clear();


            DirectoryInfo dirInfo = new DirectoryInfo( SelectedImagePath );
            FileInfo[] info = dirInfo.GetFiles();

            foreach (FileInfo fileInfo in info)
            {
                //adds files to the collection with its properties
                _fileDetails.Add( new Details
                {
                    FileName = fileInfo.Name,
                    Size = fileInfo.Length.ToString(),
                    DateCreated = fileInfo.CreationTime.ToString(),
                    DateModified = fileInfo.LastWriteTime.ToString(),
                    RevNumber = "?",
                    User = "?"
                } );

            }
        }

其中fileDetails是我的ObservableCollection。

鼠标事件:

protected void HandleDoubleClick( object sender, MouseButtonEventArgs e )
    {
        DependencyObject src = ( DependencyObject )( e.OriginalSource );
        while (!( src is Control ))
            src = VisualTreeHelper.GetParent( src );
        MessageBox.Show( "*** Double clicked on a " + src.GetType().FullName +"********************" + sender.ToString() );
    }

绑定:

<ListView Height="335" HorizontalAlignment="Right" Margin="0,12,12,0" Name="fileExplorerView" VerticalAlignment="Top" Width="509" Grid.Column="1" ItemsSource="{Binding ElementName=This, Path=fileDetails}">
        <ListView.ItemContainerStyle>
            <Style TargetType="{x:Type ListViewItem}">
                <EventSetter Event="MouseDoubleClick" Handler="HandleDoubleClick"/>
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.View>

            <GridView>
                <GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding FileName}"/>
                <GridViewColumn Header="Size" Width="100" DisplayMemberBinding="{Binding Size}"/>
                <GridViewColumn Header="Date Created" Width="100" DisplayMemberBinding="{Binding DateCreated}"/>
                <GridViewColumn Header="Time Created" Width="100" DisplayMemberBinding="{Binding DateModified}"/>
                <GridViewColumn Header="Revision Number"  Width="100" DisplayMemberBinding="{Binding RevNumber}"/>
                <GridViewColumn Header="Modified By" Width="100" DisplayMemberBinding="{Binding User}"/>

            </GridView>

        </ListView.View>
    </ListView>

而不是鼠标事件中的messageBox,我将使用一个进程来打开文件。问题是,我似乎无法弄清楚如何获取所选文件的路径。

由于

所有帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这样的东西
var item = (FrameworkElement)sender;
var file = (Details)item.DataContext;
var path = file.Path; // Your Details class should save the FileInfo.FullName!

(为什么你还有Details课?我只会使用FileInfo对象