【问题标题】:Wpf style resource for foreground color of selected listbox item所选列表框项的前景色的 Wpf 样式资源
【发布时间】:2010-10-07 05:05:24
【问题描述】:

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

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

我也想为前景色做同样的事情。

基本上ListBox的Selection模式是single的,当一个item被选中时,我只希望它被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。

At the moment, I have the background color being set to Transparent when the item is selected.由于文本默认设置为白色,因此在选择项目时它会在视觉上消失。我正在寻找一种在选择文本块时在其前景上设置颜色的方法。现在它可以是黑色的,但最终它将引用更高级别的字体颜色。

【问题讨论】:

    标签: c# wpf listboxitem


    【解决方案1】:

    这是一个使用 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 2011-08-08
      • 2016-01-01
      相关资源
      最近更新 更多