我嘗試將 CheckBox IsChecked 系結到 xaml 中 ListBoxItem 的 IsSelected。通過這種方式,我可以使用相應的復選框填充動態串列,并使用表單接收已檢查專案的串列。到目前為止,一切都很好。但是,如何以編程方式預先檢查串列中的專案,在 PowerShell 中更可取?
我一直在使用如下所示的 XAML 進行測驗:
<Window x:Class="WpfHandler.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:WpfHandler"
mc:Ignorable="d"
Title="Testing" Height="300" Width="250">
<Window.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<CheckBox Margin="5,2" IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource TemplatedParent}}">
<ContentPresenter />
</CheckBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Border Padding="10">
<Grid Margin="0 10 0 10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Name="Testing" Orientation="Horizontal">
<ListBox Name="Box_Test" ItemsSource="{DynamicResource test}" Height="220" SelectionMode="Multiple"/>
</StackPanel>
</Grid>
</Border>
</Window>
...以及如下所示的 Powershell 腳本:
add-type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Drawing
$xamlFile = "testing.xaml"
[xml]$xaml = (Get-Content $xamlFile -Raw) -replace 'x:Name', 'Name'
$xaml.Window.RemoveAttribute('x:Class')
$xaml.Window.RemoveAttribute('mc:Ignorable')
$xaml.SelectNodes("//*") | ForEach-Object {
$_.RemoveAttribute('d:LayoutOverrides')
}
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
try {
$Script:Form = [Windows.Markup.XamlReader]::Load( $reader )
# Get Name variables from form and set scope to script
$xaml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name ($_.Name) -Value $Script:Form.FindName($_.Name) -Scope script }
}
catch {
Write-Host "Unable to load Windows.Markup.XamlReader";
exit
}
$testdata = Get-Content "testdata.txt"
$Script:Form.Resources.Add("test", $testdata)
$Script:Form.ShowDialog()
uj5u.com熱心網友回復:
這是一個按索引選擇前兩項的示例:
$Script:Form.Add_Loaded({
foreach( $i in 0, 1 ) {
$Box_Test.ItemContainerGenerator.ContainerFromIndex( $i ).IsSelected = $true
}
})
$Script:Form.ShowDialog()
ItemContainerGenerator是 的ItemsControl基類的屬性ListBox。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520473.html
