2014-07-24 96 views
0

我有一个正常的ListBox,我想将选择颜色更改为红色。这是迄今为止我所拥有的。更改列表框的选择颜色项目

<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}"> 
    <Style.Resources> 
     <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
         Color="red" /> 
     <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" 
         Color="red" /> 
    </Style.Resources> 
</Style> 

它的工作。 SelectedItem是红色的,即使焦点没有对准也会保持红色。

这是我的真正问题:在我的网格中,我也有一个CheckBox,我希望上述样式仅适用于CheckBox被选中的情况。

因此,如果复选框被选中,我希望选择颜色为红色,如果CheckBox未选中,则选择蓝色(或默认颜色)。

我经历了网络,我找不到任何东西,所以我在寻求帮助。

回答

1

你可以有两个不同的风格 -

  1. 与所有的setter和触发器的默认样式。它定义

  2. 空白风格与资源,使这种风格是BasedOn默认样式,使所有setter和触发器会从默认的样式继承。

然后你就可以换ItemContainerStyle基于复选框选中状态。


样品:

<StackPanel> 
    <StackPanel.Resources> 
     <Style x:Key="myLBStyleDefault"> 
      <!-- All setters and triggers go here --> 
     </Style> 
     <Style x:Key="myLBStyleWithRed" 
       BasedOn="{StaticResource myLBBaseStyle}" 
       TargetType="{x:Type ListBoxItem}"> 
      <Style.Resources> 
       <SolidColorBrush 
        x:Key="{x:Static SystemColors.HighlightBrushKey}" 
        Color="Red" /> 
       <SolidColorBrush 
        x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" 
        Color="Red" /> 
      </Style.Resources> 
     </Style> 
    </StackPanel.Resources> 
    <CheckBox x:Name="chk"/> 
    <ListBox> 
     <ListBox.Style> 
      <Style TargetType="ListBox"> 
       <Setter Property="ItemContainerStyle" 
         Value="{StaticResource myLBStyleDefault}"/> 
       <Style.Triggers> 
        <DataTrigger Binding="{Binding IsChecked, ElementName=chk}" 
           Value="True"> 
         <Setter Property="ItemContainerStyle" 
           Value="{StaticResource myLBStyleWithRed}"/> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </ListBox.Style> 
    </ListBox> 
</StackPanel> 
0

你需要通过处理CheckBox.CheckedCheckBox.Unchecked事件做,在代码我不相信,你可以添加或使用XAML一个Trigger删除Resources。但是,properties of the SystemColors class是只读的,因此您不能直接设置它们。

有一种方法,我发现,但涉及从user32.dll导入kkk方法,所以它可能不是佯攻心。欲了解更多信息,请参阅pinvoke.net网站上的SetSysColors (user32)页面。从链接页面:

[DllImport("user32.dll", SetLastError=true)] 
public static extern bool SetSysColors(int cElements, int [] lpaElements, int [] lpaRgbValues); 
public const int COLOR_DESKTOP = 1; 

//example color 
System.Drawing.Color sampleColor = System.Drawing.Color.Lime; 

//array of elements to change 
int[] elements = {COLOR_DESKTOP}; 

//array of corresponding colors 
int[] colors = {System.Drawing.ColorTranslator.ToWin32(sampleColor)}; 

//set the desktop color using p/invoke 
SetSysColors(elements.Length, elements, colors); 

//save value in registry so that it will persist 
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Control Panel\\Colors", true); 
key.SetValue(@"Background", string.Format("{0} {1} {2}", sampleColor.R, sampleColor.G, sampleColor.B)); 
相关问题