ListBox选择的WPF中的触发器不会触发

时间:2012-02-08 19:03:56

标签: c# wpf

我从后面的代码设置列表框的选定项目如下

private void AvailableItem_Click(object sender, RoutedEventArgs e)
    {
        object clicked = (e.OriginalSource as FrameworkElement).DataContext;
        var lbi = AvailableItem.ItemContainerGenerator.ContainerFromItem(clicked) as ListBoxItem;
        lbi.IsSelected = true;
    }

我添加了一个触发器,如下所示,以更改所选的项目背景颜色

<Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Foreground" Value="White" />
                            <Setter Property="Background" Value="Black"/>
                        </Trigger>
</Style.Triggers>

这里的问题是颜色没有按预期变化。我尝试将IsSelected值的触发器添加为false并且它可以正常工作,但不会触发IsSelected true。我很困惑为什么会这样。

编辑:

以下是完整的绑定代码:

<ListBox  Height="600"  Name="AvailableItem" Width="320" Grid.Column="1" ButtonBase.Click="AvailableItem_Click" Background="#00000000" BorderBrush="LightBlue" HorizontalContentAlignment="Stretch">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="2*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <TextBlock Text="{Binding Path = SomeText}" FontSize="14" Foreground="Black" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center" Margin="0,0,0,0"/>
                        <Button Command="{Binding ElementName=root, Path=DataContext.SomeCommand}" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Right" VerticalAlignment="Bottom" Background="#BF000000" BorderBrush="Transparent" Foreground="White" Content="..." Width="25" Height="25" Margin="5,0,5,0">
                        </Button>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Foreground" Value="Yellow" />
                            <Setter Property="Background" Value="Red"/>
                        </Trigger>
                        <Trigger Property="IsSelected" Value="False">
                            <Setter Property="Foreground" Value="Black" />
                            <Setter Property="Background" Value="Transparent"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ListBox.ItemContainerStyle>

0 个答案:

没有答案