WPF / PowerShell ListBox:如果匹配*表达式,则更改项目的前景色*

时间:2017-04-21 22:46:42

标签: wpf xaml powershell

我正在尝试根据其内容更改ListBox中项目的前景色。

<ListBox x:Name="listBox_advList" HorizontalAlignment="Left" Height="277" Margin="10,38,0,0" VerticalAlignment="Top" Width="491">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Style.Triggers>
                    <Trigger Property="Content" Value="GIE">
                        <Setter Property="ListBoxItem.Background" Value="LightGreen" />
                    </Trigger>
                    <Trigger Property="Content" Value="Console Admin Tools">
                        <Setter Property="ListBoxItem.Background" Value="Orange" />
                    </Trigger>                               
                </Style.Triggers>
            </Style>
        </ListBox.ItemContainerStyle>
        </ListBox>

如果匹配'成功'或'失败',我想将每个项目的颜色更改为绿色或橙色。

换句话说,是否存在某种类型的-match或类似应用于我可以使用的触发器,以便我可以更改项目的颜色,如果包含'成功'或'失败'?

我找到了这篇文章: https://www.codeproject.com/Questions/883626/Wpf-Trigger-If-contains-value 但我不知道如何将该代码转换为WPF / XAML。

非常感谢,

特里斯坦

修改 如果它有帮助,这是代码的其余部分:

$WPF_button_getAdv.add_Click({

# Clear listBox
$WPF_listBox_advList.Items.Clear()
# Test connection
if (Test-Connection $($WPF_textBox_compName.Text) -Count 1 -ErrorAction SilentlyContinue)
    {
    # Get ADV
    $advertisement = Get-WmiObject -Query "SELECT * FROM CCM_Softwaredistribution" -Namespace "root\CCM\Policy\Machine\ActualConfig" -Computer $($WPF_textBox_compName.Text) -Authentication PacketPrivacy -Impersonation Impersonate
    # Sort ADV : Group by ADVID -> Foreach Object in the Group, select LAST element
    $global:sortAdv = $advertisement | Group-Object ADV_AdvertisementID | ForEach-Object { $_.Group | Select-Object -Last 1 }
    # Get Status
    $advStatus = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\SMS\Mobile Client\Software Distribution\Execution History" -Recurse | ForEach-Object { Get-ItemProperty -Path  $_.PsPath }
    foreach ($item in $global:sortAdv)
        {
        foreach ($value in $advStatus)
            {
            if ($value.PSPath -match $item.PKG_PackageID)
                {
                [array]$listBoxInput += "$($value._State)" + " - $($item.PKG_PackageID)" + " - $($item.PKG_Name)"
                }
            }
        }

    [array]$listBoxInput | ForEach-Object {
    $WPF_listBox_advList.AddText($_)
    }

    }
else { $WPF_textBox_compName.Text = 'Ping KO' }

})

我想要做的是根据 $ value._State 的值更改每个项目的颜色。如果它包含SUCCESS,listBox中的项应该是绿色,如果它包含FAILURE,它应该是橙色/红色...谢谢! :)

3 个答案:

答案 0 :(得分:1)

您可以在将样式加载到PowerShell后对其进行操作。您只需要找到ListBox控件,然后遍历Items,并相应地格式化它们。假设您将此控件的父级分配给变量$Form,您可以执行以下操作:

$ListBox = $Form.FindName('listBox_advList')
Switch($ListBox.Items){
    {$_.Content -match 'success'} {$_.Background = 'Green'}
    {$_.Content -match 'failure'} {$_.Background = 'Orange'}
}

答案 1 :(得分:0)

好吧,我个人不会去触发器来处理这种行为。在这种情况下,我会利用IValueConverter。使用它,我们可以获取一个绑定值,将其发送到转换器,并返回一个刷子颜色以供使用。

示例,我想转换等于&#34; SUCCESS&#34;的字符串值。返回一个绿色画笔,以及其他任何东西,返回一个红色的画笔。这就是我要做的事情:

<Window x:Class="WpfApp1.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:WpfApp1"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<!-- Declare my converter as a resource in my window -->
<Window.Resources>
    <local:StringToBrushConverter x:Key="colorConverter"></local:StringToBrushConverter>
</Window.Resources>

<!-- My window Content -->
<Grid>
    <ListBox>
        <!-- String items for listbox (This could be a binded collection of strings) -->
        <ListBox.Items>
            <sys:String>SUCCESS</sys:String>
            <sys:String>SUCCESS</sys:String>
            <sys:String>FAILURE</sys:String>
            <sys:String>SUCCESS</sys:String>
            <sys:String>FAILURE</sys:String>
        </ListBox.Items>

        <!-- Set the item template of the items, to a text block -->
        <ListBox.ItemTemplate>
            <DataTemplate>
                <!-- Bind 'Text' to the string value, bind the foreground to the returned converter value given the string -->
                <TextBlock Text="{Binding}" Foreground="{Binding Converter={StaticResource colorConverter}}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

当然,我们现在需要的只是转换器类:

public class StringToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((string)value == "SUCCESS") //Return green brush (P.S. Case sensitive)
        {
            return Brushes.Green;
        }
        else if ((string)value == "FOOBAR") //If you ever wanted other color options
        {
            return Brushes.Yellow;
        }

        //Anything not caught will be red. AKA "FAILURE" would belong here.
        return Brushes.Red;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

我认为这是一个很好的方法,比我认为使用触发器要容易得多。

答案 2 :(得分:0)

我最终使用此方法,如technet上所示: https://social.technet.microsoft.com/Forums/windows/en-US/05144c37-4991-46fa-b2d8-dcb0a7f266df/wpf-powershell-listbox-change-foreground-color-of-item-if-it-matches-expression?forum=winserverpowershell

&LT; ...&GT;

   if (cur.moveToFirst()) {
        while (cur.moveToNext()) {

效果很好,再次感谢你们!