2
<Button Content="1" Background="{Binding HotNumbers, Converter={StaticResource BrushConverter}  }"/>
<Button Content="2" Background="{Binding HotNumbers, Converter={StaticResource BrushConverter}  }"/>

..

I have 10 buttons. I am trying to bind the background color of each to an ObservableCollection<bool>. I tried using a IValueConverter to convert the boolean value to a Brush color as below.

But the whole collection seems to be passed in the object value instead of single item throwing an exception in the converter.

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
             if ((bool)value)
            {
                return Brushes.Red;
            }
            else
            {
                return Brushes.White;
            }
        }

Is there any other way to accomplish this so that I don't have to create 10 different properties for each button.

tarzan
  • 91
  • 4

2 Answers2

2

Why don't you simply add the ConverterParameter in your xaml code like this?

Background="{Binding HotNumbers, Converter={StaticResource BrushConverter}, ConverterParameter=1 } "

and then in your converter you use your object parameter to access the specific boolean item of your array like this?

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((bool)value[(int)parameter])
        {
            return Brushes.Red;
        }
        else
        {
            return Brushes.White;
        }
    }
Mattia Magosso
  • 503
  • 2
  • 9
2

I think it will work just with this:

<Button Content="1" Background="{Binding HotNumbers[0], Converter={StaticResource BrushConverter}}"/>
<Button Content="2" Background="{Binding HotNumbers[1], Converter={StaticResource BrushConverter}}"/>
Jose
  • 1,857
  • 1
  • 16
  • 34