0

Problem: A lot of Buttons 40+

for example.

<Button Background="{Binding ButtonColor1}/>
<Button Background="{Binding ButtonColor2}/>
<Button Background="{Binding ButtonColor...}/>
<Button Background="{Binding ButtonColor40}/>

I want to change the Colour via a CommandBinding. That works but i don´t want to have 40+ Methods in my ModelView.

Is there any possibility to index them like:

<Button Background="{Binding ButtonColor[1]}/>

?

So that i can access them in the ViewModel with just changing one int value. (I want to change the colors via a Command from another button. First Button1 then Button2 etc.) The Execute Method in the ModelView:

private void ChangeToBlueBackgroundExecute(object parameter)
{
this.ButtonColor = Brushes.Blue;
}

1 Answers1

0

Without too much workarounds you can define a list of brushes in XAML as StaticResource:

<Window.Resources>
    <x:Array Type="{x:Type SolidColorBrush}" x:Key="ButtonColor">
        <SolidColorBrush Color="Red"></SolidColorBrush>
        <SolidColorBrush Color="Blue"></SolidColorBrush>
        <SolidColorBrush Color="Green"></SolidColorBrush>
    </x:Array>
</Window.Resources>
<StackPanel>
    <Button Background="{Binding Source={StaticResource ButtonColor}, Path=[0]}" Content="First Button"/>
    <Button Background="{Binding Source={StaticResource ButtonColor}, Path=[1]}" Content="Second Button"/>
    <Button Background="{Binding Source={StaticResource ButtonColor}, Path=[2]}" Content="Third Button"/>
</StackPanel>

For DynamicResource, you have to use a workaround as found here:

<Window.Resources>
    <x:Array Type="{x:Type SolidColorBrush}" x:Key="ButtonColor">
        <SolidColorBrush Color="Red"></SolidColorBrush>
        <SolidColorBrush Color="Blue"></SolidColorBrush>
        <SolidColorBrush Color="Green"></SolidColorBrush>
    </x:Array>
</Window.Resources>
<StackPanel>
    <Button DataContext="{DynamicResource ButtonColor}" Background="{Binding [0]}" Content="First Button"/>
    <Button DataContext="{DynamicResource ButtonColor}" Background="{Binding [1]}" Content="Second Button"/>
    <Button DataContext="{DynamicResource ButtonColor}" Background="{Binding [2]}" Content="Third Button"/>
</StackPanel>

This method prevents you from using the DataContext property as you would normally.

Now, if you want to change one of the Background using a command, your command code would be:

private void ChangeToBlueBackgroundExecute(object parameter) {
    ((SolidColorBrush[])Resources["ButtonColor"])[(int)parameter].Color = Colors.Blue;
}

For more details on the XAML path syntax, read more here.

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29