1

我想根据从 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>
4

2 回答 2

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();
    }
于 2013-02-21T10:39:09.557 回答
0

我通过在类中创建一个新变量并在 xaml 中调用这个新变量来修复它(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);
    }
    }
于 2013-02-25T11:36:28.247 回答