2011-09-07 9 views

Respuesta

18

Uso de disparadores:

<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]


En MVVM también puede a menudo manejar esto en la vista de modelo a través de propiedades get-sólo así, por ejemplo,

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; 
    } 
} 

Luego, solo tiene que enlazar a Background.

+0

Esta es una forma muy buena de hacer esto cuando se usa wpf, si buscas un código que pueda transferirse a Silverlight, también puedes necesitar la expresión SDK para la simulación del trigger. –

22

que podría obligar a la del fondo de una propiedad en el modelo de vista el truco es usar un IValueConverter para devolver un pincel con el color sus requieren, aquí está un ejemplo que convierte un valor booleano desde el modelo de vista de un color

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 una expresión de enlace como

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

Esto funcionó mejor que la respuesta seleccionada para WPF. – tzerb

Cuestiones relacionadas