将记录添加到Listview表单事件

时间:2019-02-25 11:23:14

标签: powershell runspace

我有以下ui,并且希望将System.IO.FileWatcher事件中的数据添加到列表视图中而不会阻塞UI

[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')

# Load the WPF XAML Form
[xml]$XAML = @'
<Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="315.885" Width="325.289">
        <Grid Margin="0,0,-0.2,0.2">
        <ListView Name="lvMain" HorizontalAlignment="Left" Height="196" Margin="6,53,-302,-249" VerticalAlignment="Top" Width="297" IsSynchronizedWithCurrentItem="False"/>
        <CheckBox Name="cbDelete" Content="Verwijderen" HorizontalAlignment="Left" Height="15" Margin="6,257,-106,-272" VerticalAlignment="Top" Width="100"/>
        <Button Name="btnClose" Content="Sluiten" HorizontalAlignment="Left" Height="20" Margin="216,254,-303,-274" VerticalAlignment="Top" Width="87"/>
        <TextBox Name="tbState" HorizontalAlignment="Left" Height="28" Margin="6,20,-303,-48" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="297" FontSize="20" TextAlignment="Center" FontWeight="Bold"/>

    </Grid>
</Window>

'@


# load xaml to reader
$reader=(New-Object System.Xml.XmlNodeReader $xaml)

# render the gui
$uiHash.Window=[Windows.Markup.XamlReader]::Load( $reader )

# Connect to form objects 
$xaml.SelectNodes("//*[@Name]") | %{
    Write-Verbose -Message "Loading $($_.Name) to `$uiHash.Windows.$($_.Name)" -Verbose
    $uiHash.Item($_.Name) = $uiHash.Window.FindName($_.Name) 
}


$uiHash.Window.ShowDialog() | Out-Null

下面的部分需要在单独的线程上,因为可能会导致GUI线程崩溃。

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$FileWatcher = New-Object System.IO.FileSystemWatcher
$FileWatcher.Path = Split-Path -Path "C:\temp\input.txt"
$FileWatcher.Filter = Split-Path -Path "C:\temp\input.txt" -Leaf
$FileWatcher.EnableRaisingEvents = $true  


### DECIDE WHICH EVENTS SHOULD BE WATCHED + SET CHECK FREQUENCY  
$Changed = Register-ObjectEvent $FileWatcher Changed -MessageData $uiHash -Action {
    $FullPath = $Event.SourceEventArgs.FullPath
    $ChangeType = $Event.SourceEventArgs.ChangeType
    Write-Verbose -Verbose -Message  "$(Get-Date), $ChangeType, $FullPath"
    $uiHash.Window.Dispatcher.Invoke('Normal',[Action]{    $uiHash.lvMain.Text.Add($(Get-Date)) })
    #$uiHash.ObservableCollection.Add(1)
}

0 个答案:

没有答案