首页 文章

用于所选列表框项目的前景色的Wpf样式资源

提问于
浏览
3

背景:我正在创建一个自定义列表框,每个列表框项上都有单选按钮,所以基本上它将是一个RadioButtonList . 控件完全由代码创建 . 截至目前,控件呈现并正确运行并支持2个方向(水平/垂直) . 列表框使用ItemTemplate,它是一个带有RadioButton和TextBlock的StackPanel .

到目前为止,我已经能够通过使用将其背景设置为透明的样式来防止项目的背景颜色在选择项目时更改 .

I would like to also do the same for the foreground color.

基本上,ListBox的Selection模式是单一的,当选择一个项目时,我只希望它被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>
    

相关问题