I just tested an early PowerShell WPF example from here
#requires -version 2
Add-Type -AssemblyName PresentationFramework
[xml] $xaml = #"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="408">
<Canvas>
<Button x:Name="button1"
Width="75"
Height="23"
Canvas.Left="118"
Canvas.Top="10"
Content="Click Here" />
</Canvas>
</Window>
"#
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$target=[Windows.Markup.XamlReader]::Load($reader)
$window= $target.FindName("Window")
$control=$target.FindName("button1")
$eventMethod=$control."add_click"
$eventMethod.Invoke({$window.Title="Hello $((Get-Date).ToString('G'))"})
$target.ShowDialog() | out-null
FindName seems to return $null here. I found some posts indicating, that RegisterName is needed, but I have no idea, how to apply this here.
As far as I understand your $target is your window.
Can you try :
Clear-Host
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
[System.Windows.Window]$Window=[Windows.Markup.XamlReader]::Load($reader)
$Window.Title = "Bonjour"
$controls=$Window.Content
[System.Windows.Controls.Button]$Button = ($controls.Children)[0]
$eventMethod=$Button.add_Click
$eventMethod.Invoke({$window.Title="Hello $((Get-Date).ToString('G'))"})
$Window.ShowDialog() | out-null
------------- EDIT -------------
Here is the code working with FindName I replace Canvas by Grid :
#requires -version 2
Add-Type -AssemblyName PresentationFramework
[xml]$xaml =
#"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="408">
<Grid>
<Button x:Name="button1"
Width="75"
Height="23"
Canvas.Left="118"
Canvas.Top="10"
Content="Click Here" />
</Grid>
</Window>
"#
Clear-Host
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$target=[Windows.Markup.XamlReader]::Load($reader)
$control=$target.FindName("button1")
$eventMethod=$control.add_click
$eventMethod.Invoke({$target.Title="Hello $((Get-Date).ToString('G'))"})
$target.ShowDialog() | out-null
Related
I have an issue with getting the value (text) from ListView selected item.
Besides, I am not using MVVM, it is powershell runspace.
Here is the XAML code:
<Window x:Class="Post_Depl_App.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:Post_Depl_App"
mc:Ignorable="d"
Title="Post_Depl_App" WindowState="Maximized" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="false" Background="#0060a9">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="b2v" />
<Style x:Key="FocusTextBox" TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=NumText, Path=IsVisible}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=NumText}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<ListView Name="SiteList" Height="530" Width="700" HorizontalAlignment="Center" Margin="0,350,0,100" Background="Transparent" BorderThickness="0" VerticalAlignment="Top"
Foreground="White" FontFamily="Segoe UI SemiLight" FontSize="20"
VirtualizingStackPanel.IsVirtualizing="True" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Hidden" ScrollViewer.CanContentScroll="False" ScrollViewer.IsDeferredScrollingEnabled="True"
SelectedIndex="0">
<ListViewItem Content = "Australia"></ListViewItem>
<ListViewItem Content = "Chile"></ListViewItem>
</ListView>
And here is the powershell where I have troubles. Probably finding the right property:
$SiteCheck = $SyncHash.Window.Dispatcher.invoke([System.Func[String]{$SyncHash.SiteList.SelectedItem.ToString()})
if($SiteCheck -eq "Australia"){
(Get-Content -path C:\Post_Setup\temp.txt -Raw) -replace 'SiteVar','AU' | Set-Content -Path C:\Post_Setup\temp.txt
}
elseif($SiteCheck -eq "Chile"){
(Get-Content -path C:\Post_Setup\temp.txt -Raw) -replace 'SiteVar','CL' | Set-Content -Path C:\Post_Setup\temp.txt
}
I suppose the issue lies in this line:
$SiteCheck = $SyncHash.Window.Dispatcher.invoke([System.Func[String]{$SyncHash.SiteList.SelectedItem.ToString()})
It doesn't work for ListView or ListBox.
However this works perfectly for ComboBox:
$SiteCheck = $SyncHash.Window.Dispatcher.invoke([System.Func[String]{$SyncHash.SiteBox.Text})
Does anybody know the best way to get selected item value as a text from ListView/Box?
Thank you.
In your case the type of SelectedItem is ListViewItem. You need to get a value of ListViewItem.Content property.
You can specify SelectedValuePath which is the path (property name) in SelectedItem used to get the SelectedValue.
<ListView Name="SiteList" Height="530" Width="700" HorizontalAlignment="Center" Margin="0,350,0,100" Background="Transparent" BorderThickness="0" VerticalAlignment="Top"
Foreground="White" FontFamily="Segoe UI SemiLight" FontSize="20"
VirtualizingStackPanel.IsVirtualizing="True" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Hidden" ScrollViewer.CanContentScroll="False" ScrollViewer.IsDeferredScrollingEnabled="True"
SelectedIndex="0" SelectedValuePath="Content">
<ListViewItem Content = "Australia"></ListViewItem>
<ListViewItem Content = "Chile"></ListViewItem>
</ListView>
Now the SelectedValue contains value of ListViewItem.Content, so read it in the PowerShell.
$SiteCheck = $SyncHash.Window.Dispatcher.invoke([System.Func[String]{$SyncHash.SiteList.SelectedValue.ToString()})
I had a question along a similar topic last week which ultimatly is the same issue but in that scenario I managed to get round this with a PowerShell array on static data thanks to someone on the forum suggesting.
This time round I cant use static so I am somewhat back to my root problem.
I have created a WPF XAML form in Visual Studio and am taking this back to Powershell as my remit with the customer is 'low-code'. The item in question is loading an xml file into the form to populate a list box. Reason for a list box is cleanliness of changing the colour of the background.
Now in VS this works find with a Data Provider but for reasons I cannot find an answer to, this just simply will not work when taken back to PowerShell so I have looked for alternate way.
So I have a simple XML as below:
<?xml version="1.0"?>
<Configuration>
<AllowedAutoStart>Application 1</AllowedAutoStart>
<DenyRemoveAutoStart>Application 2</DenyRemoveAutoStart>
</Configuration>
I want to feed this into my PowerShell/XAML Hybrid Script and simply bind the contents to the appropriate list box (below code is just starting with allowed apps)
I have tried a few different ideas from across the forum before posting but none quite get there. Below is the code I have at present, it doesnt work but doesnt produce any errors either :-)
Appreciate any guidance.
# Load Assembly
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
#Declare XAML Code
[xml]$AppGeneratorWindow = #"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="App Config Generator" Height="350" Width="600" WindowStartupLocation="CenterScreen" Top="5" ResizeMode="NoResize">
<Window.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FFAA3D3D" Offset="1"/>
</LinearGradientBrush>
</Window.Background>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="115*"/>
<ColumnDefinition Width="132*"/>
<ColumnDefinition Width="543*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="381*"/>
<RowDefinition Height="241*"/>
</Grid.RowDefinitions>
<Label Name="AllProgramsLabel" Content="All Programs" HorizontalAlignment="Left" Margin="28.333,20,0,0" VerticalAlignment="Top" Foreground="#FFFEFBFB" FontSize="14" FontWeight="Bold" RenderTransformOrigin="2.696,-3.142" Grid.Column="1" Grid.ColumnSpan="2"/>
<Button Name="AddButton" Content="Add >>" HorizontalAlignment="Left" Margin="34,83,0,0" VerticalAlignment="Top" Width="166" FontWeight="Bold" FontSize="14" Height="28" BorderBrush="#FF070606" Background="#FF933838" Foreground="#FFFCFAFA" Grid.Column="3" RenderTransformOrigin="0.416,-0.906"/>
<Label Name="WindowsStartupLabel" Content="Windows Startup" HorizontalAlignment="Left" Margin="236,20,0,0" VerticalAlignment="Top" Foreground="#FFFEFBFB" FontSize="14" FontWeight="Bold" RenderTransformOrigin="2.696,-3.142" Grid.Column="3"/>
<Button Name="RemoveButton" Content="<< Remove" HorizontalAlignment="Left" Margin="34,169,0,0" VerticalAlignment="Top" Width="166" FontWeight="Bold" FontSize="14" Height="28" BorderBrush="#FF070606" Background="#FF933838" Foreground="#FFFCFAFA" Grid.Column="3" Grid.RowSpan="2" RenderTransformOrigin="0.51,-0.503"/>
<ListBox Name="AllProgramsListBox" Grid.ColumnSpan="2" Grid.Column="1" HorizontalAlignment="Left" Height="132" Margin="28,65,0,0" Background="#FFAA3D3D" VerticalAlignment="Top" Width="123" Grid.RowSpan="2"/>
<ListBox Name="StartupListBox" Grid.Column="3" HorizontalAlignment="Left" Height="132" Margin="237,65,0,0" Background="#FFAA3D3D" VerticalAlignment="Top" Width="123" Grid.RowSpan="2"/>
</Grid>
</Window>
"#
#List Boxes
$AllProgramsListBox = $window.FindName("AllProgramsListBox")
$ConfigurationFile = "$env:ProgramData\WindowsStartupTool\AutoStartConfig.XML"
[xml]$ConfigFile = Get-Content $ConfigurationFile
foreach ($entry in $ConfigFile.Configuration.AllowedAutoStart.add)
{
write-host $entry
$AllProgramsListBox.Items.Add($($entry))
}
#Declare & Create the form
$reader=(New-Object System.Xml.XmlNodeReader $AppGeneratorWindow)
$window = [Windows.Markup.XamlReader]::Load($reader)
##########################################
#Launch the User Interface #
[void]$window.ShowDialog() #
##########################################
This is launched from PowerShell which is where I have to get it to work from in some capacity.
Thanks in advance
You're very close. All you really have to do is move the part where you read the config file and do the foreach ($entry.. to below the creation of the window.
As the code is now, you're trying to use variable $window where it is not yet defined.
Directly below the XAML code put:
#Declare & Create the form
$reader = New-Object System.Xml.XmlNodeReader $AppGeneratorWindow
$window = [Windows.Markup.XamlReader]::Load($reader)
#List Boxes
$AllProgramsListBox = $window.FindName("AllProgramsListBox")
$ConfigurationFile = "$env:ProgramData\WindowsStartupTool\AutoStartConfig.XML"
[xml]$ConfigFile = Get-Content $ConfigurationFile -Raw
foreach ($entry in $ConfigFile.Configuration.AllowedAutoStart) {
Write-Host $entry
$AllProgramsListBox.Items.Add($entry)
}
##########################################
#Launch the User Interface #
[void]$window.ShowDialog() #
##########################################
I'm having the hardest time getting a value from a text box to use in another function. If I step through the script, I can see that the value is assigned to the text box, but am not able to assign it to another variable.
Here is the relevant code:
#region XMLCode
[xml]$xaml = #"
<Window 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:PayrollApp"
Title="Payroll Application" Height="450" Width="300" Margin="0,0,0,0">
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="1" Content="Computer Name:"/>
<TextBox Grid.Row="1" Name="txtComputerName" Margin="120,5,5,5" />
<Label Grid.Row="2" Content="Site ID:"/>
<TextBox Grid.Row="2" Name="txtSiteID" Margin="120,5,5,5"/>
<Label Grid.Row="3" Content="Payroll ID:"/>
<TextBox Grid.Row="3" Name="txtPayrollID" Margin="120,5,5,5"/>
<Label Grid.Row="4" Content="Email From Address:"/>
<TextBox Grid.Row="4" Name="txtFromAddress" Margin="120,5,5,5"/>
<Separator Grid.Row="5" Margin="5"/>
<TabControl Grid.Row="6" Margin="5">
<TabItem Header="Daily Payroll">
<StackPanel Background="LightGray">
<TextBlock FontSize="12" Margin="5" TextWrapping="Wrap">
Use this form to re-run the Daily Payroll file.
</TextBlock>
<TextBlock TextWrapping="Wrap" FontSize="12" Margin="5,0">
Enter the dates (YYYYMMDD) needed in the boxes below and press "Send"
</TextBlock>
<TextBox Name="txtDaily1" Margin="5,10,5,5"/>
<TextBox Name="txtDaily2" Margin="5"/>
<TextBox Name="txtDaily3" Margin="5"/>
<TextBox Name="txtDaily4" Margin="5"/>
<TextBox Name="txtDaily5" Margin="5"/>
<Button Name="btnDailySend" Margin="5" Width="75" Background="BurlyWood">Send</Button>
</StackPanel>
</TabItem>
<TabItem Header="Weekly Payroll">
<StackPanel Background="LightGray">
<TextBlock FontSize="12" Margin="5" TextWrapping="Wrap">
Use this form to re-run the Weekly Payroll file.
</TextBlock>
<TextBlock TextWrapping="Wrap" FontSize="12" Margin="5,0">
Enter the date of the payroll period (Wednesday) (YYYYMMDD) and press "Send"
</TextBlock>
<TextBox Name="txtWeekly" Margin="5"/>
<Button Name="btnWeeklySend" Margin="5,10" Width="75" Background="BurlyWood">Send</Button>
</StackPanel>
</TabItem>
</TabControl>
</Grid>
</Grid>
</Window>
"#
#endregion
#region LoadWindow
#Read the XAML file
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
try {
$window = [Windows.Markup.XamlReader]::Load($reader)
}
catch {
ThrowError -ErrorObj $_
}
# Create variables based on form control names
# Variable will be named as 'var_<control name>'
$xaml.SelectNodes("//*[#Name]") | ForEach-Object {
#"trying item $($_.Name)"
try {
Set-Variable -Name "var_$($_.Name)" -Value $window.FindName($_.Name) -ErrorAction Stop
}
catch {
ThrowError $_
}
}
# Get-Variable var_*
#endregion
#region EventsAndMethods
$window.Add_Loaded({
# Get the site information
GetSiteInformation
# Populate the text boxes
$var_txtComputerName.Text = $computer
$var_txtPayrollID.Text = $global:payid
$var_txtSiteID.Text = $global:SiteNum
$var_txtFromAddress.Text = $script:from
# Get the number of daily text boxes
$global:numDailyTextBox = (Get-Variable -Name "var_txtDaily*").Count
})
$var_btnDailySend.Add_Click({
# Email contents
$body = "PeopleSoft Team,`r`nHere are the time punch files that need to be uploaded to PeopleSoft.`r`nThanks."
$sub = "cctime Files for $sitename $payrollid"
$timefiles = #()
# Run the Payroll
$dailyTextBox = #(Get-Variable -Name "var_txtDaily*")
foreach ($textBox in $dailyTextBox) {
if ([string]::IsNullOrEmpty($textBox.Text)) {
continue
}
$date = $textBox.Text
RunDailyPayroll -day $date
LogInfo "Moving time file to C:\TA"
Move-Item -Path "$script:filepath\$script:dailyfile" -Destination $scriptPath -Force -Verbose
}
LogInfo "Sending email"
Send-MailMessage -To $emailTo -From $script:from -SmtpServer $server -Subject $sub -Body $body -Attachments "$scriptPath\$script:dailyfile" -Verbose
LogInfo "Email sent"
[Microsoft.VisualBasic.Interaction]::MsgBox("Email sent!", "OkOnly", "Email sent")
})
The issue is in the $var_btnDailySend.Add_Click event. There are 5 text boxes where the user will enter data into 1 or more of them. I then want to use that value in the RunDailyPayroll function. But I cannot assign that value to another variable. When stepping through, the value is: System.Windows.Controls.Text::<value entered>. How can I convert that to a string of just the <value entered>? And I've tried $date = $textBox.Text.ToString(), which just throws an error.
Thanks.
You should be able to extract the text with
$TextBox.Value.Text
I have a WPF form that opens a textbox for user input, going for a line seperated list of PC names. No matter how I try separating them the values all end coming back as a single item, a mutli-line item sure, but one item. I can't get those to go into my array one line at a time.
Here's the XAML along with a few of the things I've tried through many attempts to get this into my array. Note that the textbox.lines doesn't seem to return anything though I read that's might work for my needs.
$inputXML = #"
<Window x:Name="Add_to_AD_Group" x:Class="Form.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:MSIForm"
mc:Ignorable="d"
Title="Add to AD for SCCM Deployment" Height="327.57" Width="283.937">
<Grid RenderTransformOrigin="0.511,0.499">
<TextBox x:Name="MachinesList" HorizontalAlignment="Left" Height="155" Margin="62,100,0,0" VerticalAlignment="Top" Width="163" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Enter Machine list below" VerticalAlignment="Top" Margin="62,73,0,0" Height="22" Width="163"/>
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Select AD Group" VerticalAlignment="Top" Margin="62,10,0,0" Height="24" Width="163"/>
<ComboBox x:Name="ADGroupsList" HorizontalAlignment="Left" Margin="62,39,0,0" VerticalAlignment="Top" Width="163" IsEditable="True"/>
<Button x:Name="OK" Content="OK" HorizontalAlignment="Left" Margin="46,268,0,0" VerticalAlignment="Top" Width="75"/>
<Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Left" Margin="161,268,0,0" VerticalAlignment="Top" Width="75" IsCancel="True"/>
</Grid>
</Window>
"#
$TempVar = $WPFMachinesList.Text
$TempVar = $TempVar.Trim()
# = $TempVar.Split([Environment]::NewLine)
#, [StringSplitOptions]::RemoveEmptyEntries
#foreach ($item in $TempVar) {$Machinearray += $item}
#$TempVar = ($TempVar -split '/r?/n').Trim()
Out-GridView -InputObject $TempVar -Title "WPF Machines List"
The out-GridView displays something like this:
Out-Gridview test
Thanks for any help!
Update: I am trying to get a list of machines back from the Textbox to run through a set of command for each machine name, I have tried all kinds of string manipulation and cannot get the list as individual items it comes back as a single item from the textbox. For my XAML, I use VS to get this xaml code and powershell around it to launch it and modify it. E.g. I have powershell getting a list of groups from an OU, and use that to populate the combobox, then the list of machines would be added to the selected group, so there is no more to the xaml code itself than this. Here's the full xaml function if that helps determine what I'm doing wrong.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("presentationframework")
Function Get-MachineList {
$inputXML = #"
<Window x:Name="Add_to_AD_for_SCCM_Deployment" x:Class="Form.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:MSIForm"
mc:Ignorable="d"
Title="Add to AD for SCCM Deployment" Height="327.57" Width="283.937">
<Grid RenderTransformOrigin="0.511,0.499">
<TextBox x:Name="MachinesList" HorizontalAlignment="Left" Height="155" Margin="62,100,0,0" VerticalAlignment="Top" Width="163" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Enter Machine list below" VerticalAlignment="Top" Margin="62,73,0,0" Height="22" Width="163"/>
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Select AD Group" VerticalAlignment="Top" Margin="62,10,0,0" Height="24" Width="163"/>
<ComboBox x:Name="ADGroupsList" HorizontalAlignment="Left" Margin="62,39,0,0" VerticalAlignment="Top" Width="163" IsEditable="True"/>
<Button x:Name="OK" Content="OK" HorizontalAlignment="Left" Margin="46,268,0,0" VerticalAlignment="Top" Width="75"/>
<Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Left" Margin="161,268,0,0" VerticalAlignment="Top" Width="75" IsCancel="True"/>
</Grid>
</Window>
"#
$inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace "x:C", "C" -replace '^<Win.*', '<Window'
[xml]$XAML = $inputXML
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
try{$Form=[Windows.Markup.XamlReader]::Load($reader)}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed."
Write-Host $_.Exception.Message;exit}
#===========================================================================
# Load XAML Objects In PowerShell
#===========================================================================
$xaml.SelectNodes("//*[#Name]") | %{Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)}
Function Get-FormVariables{
if ($global:ReadmeDisplay -ne $true){Write-host "If you need to reference this display again, run Get-FormVariables" -ForegroundColor Yellow;$global:ReadmeDisplay=$true}
write-host "Found the following interactable elements from our form" -ForegroundColor Cyan
get-variable WPF*
}
Get-FormVariables{
}
#===========================================================================
# Actually make the objects work
#===========================================================================
$Script:GroupsList = Get-ADObject -Filter 'ObjectClass -eq "group"' -SearchBase "OU=Applications,OU=Groups,OU=AAM-Enterprise,DC=AAM,DC=NET" -Credential $creds | sort
foreach ($group in $GroupsList) {$WPFADGroupsList.Items.Add($group.Name)}
$WPFOK.Add_Click{
$TempVar = ($WPFMachinesList.Text).Trim()
#$TempVar = #(($TempVar.Trim()) -split "`r`n,")
# = $TempVar.Split([Environment]::NewLine)
#, [StringSplitOptions]::RemoveEmptyEntries
#foreach ($item in $TempVar) {$Machinearray += $item}
Out-GridView -InputObject $TempVar -Title "WPF Machines List"
#foreach ($machine in $TempVar) {
#$line = $line | Out-String
#$MachineArray = #()
#$MachineArray += $($line)}
#VerifySCCMClient $machine
#Get-SelectedGroup
#}
}
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{
$Error.Clear()
$ADSCCMForm.Close()
}
}
)
#Sample entry of how to add data to a field
#$vmpicklistView.items.Add([pscustomobject]#{'VMName'=($_).Name;Status=$_.Status;Other="Yes"})
#===========================================================================
# Shows the form
#===========================================================================
Write-Host "To show the form, run the following" -ForegroundColor Cyan
$Form.ShowDialog() | Out-Null
}
Get-MachineList
You had everything needed:
a trimed string
a split for [environment]::NewLine
[System.StringSplitOptions]"RemoveEmptyEntries" to get rid of empty lines.
Put it together and the line looks like this:
$TempVar = ($WPFMachinesList.Text.Trim()).split([environment]::NewLine,[System.StringSplitOptions]"RemoveEmptyEntries")
This will create an array from the lines you entered in the textbox.
I am trying to create a simple Datagrid using WPF such that each row has a checkbox. I am having a tough time while retrieving the data. I am getting only 1 result. What can I fix in the below XAML
<DataGrid x:Name="details" x:Uid="MyDataGrid" AutoGenerateColumns="False" AlternationCount="1" SelectionMode="Single" IsReadOnly="True" HeadersVisibility="Column" Margin="0,0,10,2" HorizontalAlignment="Right" Width="410" Grid.Column="1" Grid.Row="1" >
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<CheckBox Content=" Select All" x:Name="headerCheckBox" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chkDiscontinue" IsChecked="{Binding Path=IsChecked,ElementName=headerCheckBox,Mode=OneWay}" Margin="45 2 0 0" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding Path=file_name}" Header="File Name" Width="2*" IsReadOnly="True" />
<DataGridTextColumn Binding="{Binding Path=file_path}" Header="File Path" Width="0.9*"/>
</DataGrid.Columns> </DataGrid>
This is how I am trying to retrieve:
$inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace '^<Win.*', '<Window'
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = $inputXML
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed."}
#===========================================================================
# Store Form Objects In PowerShell
#===========================================================================
#$xaml.SelectNodes("//*[#Name]") | %{Set-Variable -Name "var_$($_.Name)" -Value $Form.FindName($_.Name) -Scope Global }
$xaml.SelectNodes("//*[#Name]") | %{Set-Variable -Name "var_$($_.Name)" -Value $Form.FindName($_.Name) }
$var_search_button.Add_Click({
#JUST TO DISPLAY SOME RANDOM DATA(IT WORKS)
$t = Import-Csv .\imp.csv
$t | Select #{name = "file_name"; ex={$_.id}},#{name = "file_path"; ex={$_.name}} |% {$var_details.AddChild($_)}
#TRYING TO RETRIVE THE ROWS WHICH I CHECK IN UI
echo "__Show FORM DATA" | Out-File "imp.txt"
$var_details.SelectedCells | Out-File "imp.txt" -Append
$var_details.SelectedItems | Out-File "imp.txt" -Append
})
$Form.ShowDialog() | out-null
#-------------------------------------
I'm not used to use PowerShell but... talking about XAML, having your "IsChecked" property set to "True" isn't the same as being selected.
You should set your row to be selected everytime you check it.
$var_details.SelectedCells | Out-File "imp.txt" -Append
$var_details.SelectedItems | Out-File "imp.txt" -Append
You are asking for SelectedCells/SelectedItems and when you check you don't say they are selected.
I hope I explained myself :)