根据绑定项目更改按钮的颜色

问题描述:

我对绑定到类的按钮具有此xaml。我向该类中添加了另一个属性,并且如果该属性的值大于零,则该按钮的背景颜色为黄色。根据绑定项目更改按钮的颜色

<local:TileView x:Key="Button_Available_View"> 
    <local:TileView.ItemTemplate> 
    <DataTemplate> 
     <Grid> 
     <Button 
      Command="command:Command_Button_AvailableTags.Command" 
      CommandParameter="{Binding Path=Name}" 
      Content="{Binding Path=Name}" 
      Tag="{Binding Path=Name}" 
      HorizontalAlignment="Stretch" 
      Padding="3,1,3,1" 
      Margin="0" 
      HorizontalContentAlignment="Center" 
      /> 
     </Grid> 
    </DataTemplate> 
    </local:TileView.ItemTemplate> 
</local:TileView> 

我该如何修改?

+2

将颜色绑定到属性,但然后需要转换器才能返回颜色。 – Paparazzi 2012-02-10 21:36:45

到目前为止,我想出了:

Background="{Binding Path=BackColor}" 

然后在后面绑定类代码:

public Brush BackColor 
{ 
    get 
    { 
     if (SimilarHits > 0) return Brushes.Yellow; 
     return Brushes.WhiteSmoke; 
    } 
} 

我不明白WPF,看来你得写20行说"hello world"

标记此答案 - 获得所需结果的代码量最少。

This应该给你一些很好的例子来解决。它的本质是你需要使用风格触发器来确定你的背景应该是哪种颜色。

最简单的方法是在绑定上创建一个IValueConverter,将属性的值转换为颜色,或者在您的项目样式中使用DataTrigger来设置基于值的颜色?

+0

我更喜欢datatrigger,因为它不需要隐藏代码。 – mydogisbox 2012-02-10 21:44:17

您必须将按钮的Foreground属性绑定到视图模型的属性。然后,您可以使用转换器将该值转换为彩色。

转换器应该是这样的:

public class TextToColorConverter: IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if (((int)value) > 0) 
       return Brushes.Yellow; 
      else 
       // for default value 
       return Brushes.Blue; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      // no need to implement it 
      throw new NotImplementedException(); 
     } 

    } 

编辑:更新绑定的背景而不是前景 的XAML将是XAML:

<Button 
    Background="{Binding Path=Property, Converter={StaticResource textToColorConverter}}"     Command="command:Command_Button_AvailableTags.Command"    CommandParameter="{Binding Path=Name}"   Content="{Binding Path=Name}"   Tag="{Binding Path=Name}"   HorizontalAlignment="Stretch"   Padding="3,1,3,1"   Margin="0"   HorizontalContentAlignment="Center"   /> 

当然,你必须将转换器作为静态资源添加到页面。

+0

其实需要绑定背景不是前景 – Paparazzi 2012-02-11 02:31:31

+0

我倒是投了你的答案。如果你会改变你的答案,我可以删除反对票。 – Paparazzi 2012-02-11 03:12:46

+0

那么你可以绑定到背景。我将在答案中进行编辑,以便您可以删除投票:) – 2012-02-11 04:48:35