选中ListBox项的前景颜色的WPF样式资源

3
背景: 我正在创建一个自定义列表框,每个列表框项上都有单选按钮,因此它实际上将成为一个RadioButtonList。该控件完全是通过代码创建的。目前,该控件呈现和行为正确,并支持2个方向(水平/垂直)。列表框使用一个ItemTemplate,其中包含一个RadioButton和一个TextBlock的StackPanel。
到目前为止,我已经能够通过使用样式将其背景设置为透明来防止项目的背景色在选择项目时发生变化。 我也想对前景色做同样的事情。 基本上,ListBox的选择模式是单个,当选择项目时,我只希望它由RadioButton反映。
我正在使用以下代码来设置ItemContainerStyle:
System.Windows.Style style =  
    new System.Windows.Style(typeof(System.Windows.Controls.ListBoxItem));  

System.Windows.Media.SolidColorBrush brush =  
    new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Transparent);  

style.Resources.Add(System.Windows.SystemColors.HighlightBrushKey, brush);

我的模板中的TextBlock是使用System.Windows.FactoryFrameworkElement创建的,如下所示:
System.Windows.FrameworkElementFactory factoryTextBlock =   
    new System.Windows.FrameworkElementFactory(typeof(System.Windows.Controls.TextBlock));
factoryTextBlock.SetBinding(System.Windows.Controls.TextBlock.TextProperty, new System.Windows.Data.Binding("Description"));  
factoryStackPanel.AppendChild(factoryTextBlock);

然后将FactoryTextBox添加到FactoryStackPanel中,并将其设置为ListBox的ItemTemplate。

目前,当项目被选中时,背景颜色被设置为透明。由于文本默认设置为白色,所以在项目被选中时,文本在视觉上消失了。我正在寻找一种方法,在文本块被选中时设置前景色。现在可以是黑色,但最终它将引用更高级别的字体颜色。

1个回答

6
这里提供一个使用XAML的示例,具体的C#代码翻译请由您自己完成。
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:sys="clr-namespace:System;assembly=mscorlib"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid.Resources>
        <x:Array x:Key="data" Type="{x:Type sys:String}">
            <sys:String>sphinx</sys:String>
            <sys:String>of</sys:String>
            <sys:String>black</sys:String>
            <sys:String>quartz</sys:String>
        </x:Array>
    </Grid.Resources>
    <ListBox ItemsSource="{StaticResource data}">
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBoxItem}">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Foreground" Value="Pink"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ListBox.Resources>
    </ListBox>
</Grid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接