根据从Binding接收的数据,在XAML中更改颜色StackPanel

时间:2013-02-21 09:39:46

标签: xaml windows-phone-8

我想根据从Binding(值)收到的数据(1,2,3 ...)更改StackPanel的颜色,我应该使用哪个?

<StackPanel Grid.Column="1">
   <Border Height="50" Width="Auto" Margin="3" Background="Black">
      <TextBlock FontSize="18" FontWeight="Bold" TextWrapping="Wrap" Foreground="White" 
                 Text="{Binding valor}" VerticalAlignment="Center"
                 HorizontalAlignment="Center"/>
   </Border>
</StackPanel>

2 个答案:

答案 0 :(得分:4)

使用转换器: http://www.smallandmighty.net/blog/using-value-converters-to-change-the-visibility-of-a-control

<Window.Resources>
    <converters:ColorConverter x:Key="ColorConverter"/>
</Window.Resources>

XAML:

  <StackPanel Background="{Binding valor, Converter={StaticResource ColorConverter}}"/>

您的转换器看起来像这样:

public class ColorConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,CultureInfo culture)
    {
        if (value != null)
        {
            int Value = (int)value;

            if(Value == 1)
               return Colors.Green;
             else if(Value == 2)
               return Colors.Red;
[...]
            }

        return null;
    }

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

答案 1 :(得分:0)

我通过在类中创建一个新变量并在xaml中调用new来修复它(Background =“{Binding customBackground}”)

public object customBackground
    {
    get
    {
    if (color == "1")//GREEN 
        {
            return new SolidColorBrush(Color.FromArgb(255, 7, 166, 45));
        }
    if (color == "2")//RED
        {
            return new SolidColorBrush(Color.FromArgb(255, 230, 5, 10));
        }
    if (color == "3")//BLUE
    {
        return new SolidColorBrush(Color.FromArgb(255, 6, 102, 210));
    }
    if (color == "4")//YELLOW
    {
        return new SolidColorBrush(Color.FromArgb(255, 189, 211, 3));
    }
    // Color por defecto
    return new SolidColorBrush(Colors.Gray);
    }
    }