2011-09-07 14 views

risposta

18

utilizzando i trigger:

<Button> 
    <Button.Style> 
     <Style TargetType="Button"> 
      <!-- Set the default value here (if any) 
       if you set it directly on the button that will override the trigger --> 
      <Setter Property="Background" Value="LightGreen" /> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding SomeConditionalProperty}" 
          Value="True"> 
        <Setter Property="Background" Value="Pink" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </Button.Style> 
</Button> 

[Regarding the note]


In MVVM è anche possibile gestire questo spesso nel modello visualizzazione tramite get-proprietà di sola così, ad esempio,

public bool SomeConditionalProperty 
{ 
    get { /*...*/ } 
    set 
    { 
     //... 

     OnPropertyChanged("SomeConditionalProperty"); 
     //Because Background is dependent on this property. 
     OnPropertyChanged("Background"); 
    } 
} 
public Brush Background 
{ 
    get 
    { 
     return SomeConditinalProperty ? Brushes.Pink : Brushes.LightGreen; 
    } 
} 

Poi basta legano a Background.

+0

Questo è un modo molto carino per farlo quando si usa wpf, se si cerca codice che possa portarsi su silverlight, si può anche richiedere l'espressione SDK per il trigger symantics –

22

si potrebbe associare il fondo a una proprietà sul ViewModel il trucco è quello di utilizzare un IValueConverter per restituire un pennello con il colore il vostro bisogno, ecco un esempio che converte un valore booleano dal ViewModel ad un colore

public class BoolToColorConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value == null) 
     { 
      return new SolidColorBrush(Colors.Transparent); 
     } 

     return System.Convert.ToBoolean(value) ? 
      new SolidColorBrush(Colors.Red) 
      : new SolidColorBrush(Colors.Transparent); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

con un'espressione vincolante come

"{Binding Reviewed, Converter={StaticResource BoolToColorConverter}}" 
+0

Questo ha funzionato meglio della risposta selezionata per WPF. – tzerb