2012-12-30 37 views
0

我有一個ListView有一些價值。 我想改變的ListView字體顏色,但是這個代碼不工作:布爾DataTrigger

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:sys="clr-namespace:System;assembly=mscorlib" 
    DataContext="{Binding RelativeSource={RelativeSource Self}}" 
    Title="Navi" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="603" Width="1029" 
    ShowInTaskbar="True" Closing="Window_Closing" Background="#FFD6D6D6"> 
<Window.Resources> 

    <Style TargetType="{x:Type TextBlock}"> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding DarkTheme}" Value="True"> 
       <Setter Property="Control.Foreground" Value="Red"/> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 

CS:

public Int32 DarkTheme {get; set;} 
    //First init 
    public MainWindow() 
    { 
     DarkTheme = 1; 
     //Init component 

我在做什麼錯?

回答

1

DarkThemeInt32更改爲bool

public bool DarkTheme {get; set;} 


DarkTheme = true; 

或者

您還可以創建Converter可以在Binding使用。

public class IntToBooleanConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
     if (value is int) 
     { 
      if ((int)value) == 1) 
       return true; 
      return false; 
     } 

     return DependencyProperty.UnsetValue; 
     } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value is bool) 
     { 
      if ((bool)value)) 
       return 1; 
      return 0; 
     } 

     return DependencyProperty.UnsetValue; 
    } 
+0

對不起,我用這個代碼public bool DarkTheme {get;設置;} DarkTheme = true; 問題沒有解決 – xnim

+1

'DarkTheme'應該屬於'DataContext'而不是'MainWindow'類。如果你是全新的,請閱讀[this](http://rachel53461.wordpress.com/2012/07/14/what-is-this-datacontext-you-speak-of/) – Tilak

+0

你是對的。謝謝 – xnim