wpf - PowerShell 和 XAML 数据绑定
问题描述
我正在尝试获取按姓氏属性搜索的用户列表,并将它们列在 ListView 中。
这是 XAML 代码:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Find users with SamAccountName"
Width="525"
Background="#FF262626"
ResizeMode="NoResize"
SizeToContent="Height">
<StackPanel Margin="5,5,5,5" Orientation="Vertical">
<Grid
Name="Grid"
Width="400"
Height="200"
Background="#313130">
<Label
Name="Label"
Content="Select employee"
FontSize="12"
Foreground="White" />
<ListView
Name="ListView"
Margin="0,25,0,0"
Background="Transparent"
BorderBrush="Transparent"
Foreground="White"
IsHitTestVisible="False"
SelectionMode="Single">
<ListView.View>
<GridView>
<GridViewColumn
Width="100"
DisplayMemberBinding="{Binding Path=Logon}"
Header="Logon" />
<GridViewColumn
Width="150"
DisplayMemberBinding="{Binding Path=FirstName}"
Header="First name" />
<GridViewColumn
Width="150"
DisplayMemberBinding="{Binding Path=LastName}"
Header="Last name" />
</GridView>
</ListView.View>
</ListView>
</Grid>
<StackPanel HorizontalAlignment="Right">
<Button Width="50" Content="SAVE" />
</StackPanel>
</StackPanel>
它看起来像这样: XAML 外观
我相信如果没有数据绑定我就无法做到这一点,并且我看到了很多关于它们的帖子,但我无法完全理解它。
现在在powershell中我有:
Add-Type -AssemblyName PresentationFramework
$employees = Get-ADUser -Filter {Surname -like "surname"}
$itemSource = @()
ForEach ($employee in ($employees | Sort-Object SamAccountName)) {
$itemSource += [PSCustomObject]@ {
Logon = $employee.Name
FirstName = $employee.GivenName
LastName = $employee.Surname
}
$columnOrder = 'Logon', 'FirstName', 'LastName'
[XML]$Form = Get-Content "xmlPath"
$NR = (New-Object System.Xml.XmlNodeReader $Form)
$Win = [Windows.Markup.XamlReader]::Load($NR)
$Win.ShowDialog()
现在,ForEach 工作得非常好,并且完全返回了我需要的东西,但找不到任何方法将它放入 ViewList。
然后我需要将选定的用户保存到稍后在文本框中显示的变量中。
对不起,如果这是一个愚蠢/简单的问题,但我刚刚开始学习 PowerShell 来帮助我自动化我的工作。
解决方案
在加载的表单中,您必须指定 ListView 的 ItemsSource
在 PowerShell 中,您可以这样做
Add-Type -AssemblyName PresentationFramework
$employees = Get-ADUser -Filter {Surname -like "surname"}
$itemSource = @()
ForEach ($employee in $($employees | Sort-Object SamAccountName)) {
$itemSource += [PSCustomObject]@{
Logon = $employee.Name
FirstName = $employee.GivenName
LastName = $employee.Surname
}
}
[XML]$Form = (Get-Content "C:\temp\test.xaml")
$NR = (New-Object System.Xml.XmlNodeReader $Form)
$Win = [Windows.Markup.XamlReader]::Load($NR)
# this part
($win.FindName("ListView")).ItemsSource = $itemSource
$Win.ShowDialog()
推荐阅读
- java - JavaFX:FXML如何使按钮占据父容器的整个宽度
- svelte - 将 node_modules 中的 css 导入到 svelte
- chart.js - Chartjs - 同一行上的水平条两个值
- html - Bootstrap 4:在移动屏幕上重新排列内部堆叠的列
- java - 在另一个 maven 项目中使用 maven 实现项目
- r - 有没有办法防止在 Windows 中运行的 Shiny App 中的目录遍历攻击?
- android - 如何验证离线缓存数据和来自 API 的数据
- java - 如何为 Retrofit 中的挂起功能创建调用适配器?
- android - RecyclerView 的监听器被应用到其他 RecyclersView
- node.js - 如何在 passport.js 中手动调用 SerializeUser?