2009-02-12 47 views
3

背景: 我正在創建一個自定義列表框,每個列表框項目上都有單選按鈕,所以本質上它將是一個RadioButtonList。該控件完全由代碼創建。截至目前,控件呈現和行爲正確並支持2個方向(水平/垂直)。該列表框使用一個帶有RadioButton和TextBlock的StackPanel的ItemTemplate。所選列表框項目的前景色的Wpf樣式資源

到目前爲止,通過使用將背景設置爲透明的樣式來選擇項目時,我已能夠防止項目的背景顏色發生變化。

我也想爲前景色做同樣的事情。

基本上,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); 

使用這樣的System.Windows.FactoryFrameworkElement創建我的模板的TextBlock的:

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。

此刻,當選擇該項目時,我將背景顏色設置爲透明。由於默認情況下文本被設置爲白色,所以在選擇該項目時它會視覺上消失。我正在尋找一種方法來設置文本塊的前景顏色,當它被選中。目前它可以是黑色的,但最終它會在更高的層次上引用字體顏色。

回答

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>