Search code examples
wpfobservablecollectionivalueconverterwpf-brushes

WPF multi-button backgroundcolor change


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


Solution

  • 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}}"/>