Хороший и простой вопрос, но минное поле ответов c # в Google, которое имеет смысл для такого PowerShell, как я (мне нужно учиться!)
У меня есть richtextbox, созданный с использованием XAML, и я быхотелось бы иметь возможность добавлять строки другим цветным шрифтом.
Большинство результатов Saipen предполагают $ formLogReport.SelectionColor, но такого свойства не существует.
Я действительно нашел то, чтоработает, но это излишне и выходит за рамки того, что я знаю о PowerShell - я не хочу использовать код, который я не понимаю.
http://vcloud -lab.com / records / powercli / powershell-gui-format-text-on-textbox-and-richtextbox
Для справки в приведенном ниже коде используется функция из предоставленной ссылки.
[void][System.Reflection.Assembly]::LoadWithPartialName( 'presentationframework' )
[void][System.Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )
[xml]$xaml = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="RichTextBox Example" Height="530" Width="740" >
<Grid Name="GridName">
<Label Name="SetupLabel" Content="Setup type" FontSize="11" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="30,25,30,30" Height="25" Width="320" />
<ComboBox Name="SetupList" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="30,55,30,30" Height="25" Width="320" />
<Label Name="SubsiteLabel" Content="Text in here will be a different size" FontSize="11"
HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,265,30,30" Height="25" Width="320" />
<TextBox Name="SubsiteBox" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,295,0,0"
Height="25" Width="320" TextWrapping="Wrap" TextAlignment="Left" VerticalContentAlignment="Center" />
<Label Name="StuffLabelLabel" Content="Enter Stuff to show up" FontSize="11"
HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,345,30,30" Height="25" Width="320" />
<TextBox Name="StuffBox" FontSize="11" HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="30,375,0,0" Height="25" Width="320" TextWrapping="Wrap" TextAlignment="Left"
VerticalContentAlignment="Center" />
<Label Name="LogLabel" Content="Log..." HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="11"
Margin="390,25,0,0" Height="25" Width="320" />
<RichTextBox Name="LogReport" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="390,55,0,0"
Height="345" Width="300" >
<FlowDocument>
<Paragraph>"HI THERE"
<Run Text=""/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Name="GoButton" Content="Go!" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="625,435,0,0"
Height="25" Width="65" IsEnabled="False" />
</Grid>
</Window>
'@
$reader = ( New-Object System.Xml.XmlNodeReader $xaml )
try {
$Form = [Windows.Markup.XamlReader]::Load( $reader )
}
catch {
Write-Warning "Unable to parse XML, with error: $( $Error[0] )`n "
}
#===========================================================================
# Load XAML Objects / Form Changes & Conditions
#===========================================================================
$xaml.SelectNodes( "//*[@Name]") | ForEach-Object { Set-Variable -Name "form$( $_.Name )" -Value $Form.FindName( $_.Name ) }
function Format-RichTextBox {
#https://msdn.microsoft.com/en-us/library/system.windows.documents.textelement(v=vs.110).aspx#Propertiesshut
param (
[parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[System.Windows.Controls.RichTextBox]$RichTextBoxControl,
[String]$Text,
[String]$ForeGroundColor = 'Black',
[String]$BackGroundColor = 'White',
[String]$FontSize = '12',
[String]$FontStyle = 'Normal',
[String]$FontWeight = 'Normal',
[Switch]$NewLine
)
$ParamOptions = $PSBoundParameters
$RichTextRange = New-Object System.Windows.Documents.TextRange( $RichTextBoxControl.Document.ContentEnd, $RichTextBoxControl.Document.ContentEnd )
if ($ParamOptions.ContainsKey('NewLine')) {
$RichTextRange.Text = "`n$Text"
}
else {
$RichTextRange.Text = $Text
}
$Defaults = @{ForeGroundColor='Black';BackGroundColor='White';FontSize='12'; FontStyle='Normal'; FontWeight='Normal'}
foreach ($Key in $Defaults.Keys) {
if ($ParamOptions.Keys -notcontains $Key) {
$ParamOptions.Add($Key, $Defaults[$Key])
}
}
$AllParameters = $ParamOptions.Keys | Where-Object {@('RichTextBoxControl','Text','NewLine') -notcontains $_}
foreach ($SelectedParam in $AllParameters) {
if ($SelectedParam -eq 'ForeGroundColor') {$TextElement = [System.Windows.Documents.TextElement]::ForegroundProperty}
elseif ($SelectedParam -eq 'BackGroundColor') {$TextElement = [System.Windows.Documents.TextElement]::BackgroundProperty}
elseif ($SelectedParam -eq 'FontSize') {$TextElement = [System.Windows.Documents.TextElement]::FontSizeProperty}
elseif ($SelectedParam -eq 'FontStyle') {$TextElement = [System.Windows.Documents.TextElement]::FontStyleProperty}
elseif ($SelectedParam -eq 'FontWeight') {$TextElement = [System.Windows.Documents.TextElement]::FontWeightProperty}
$RichTextRange.ApplyPropertyValue($TextElement, $ParamOptions[$SelectedParam])
}
}
$formstuffbox.Add_KeyDown( {
If ( $args[1].key -eq 'Return' ) {
$formLogReport.AppendText( "$( $formstuffbox.text )`n" )
}
} )
$formsubsitebox.Add_KeyDown( {
If ( $args[1].key -eq 'Return' ) {
Format-RichTextBox -RichTextBoxControl $formLogReport -Text $formsubsitebox.text -ForeGroundColor Red
}
} )
$form.ShowDialog()
Кто-нибудь знает оболее простой метод?Он будет использоваться только для ошибок, поэтому всегда должен становиться красным.