Reputation: 2146
I'm developing a MVVM app with an RGB selector. I have 3 sliders for each channel and would like to use routed events to catch the ValueChanged
event on each slider
<StackPanel Grid.Row="0" Grid.Column="1" Slider.ValueChanged="DoSmth">
<Slider Value="{Binding R}" Minimum="0" Maximum="255" />
<Slider Value="{Binding G}" Minimum="0" Maximum="255" />
<Slider Value="{Binding B}" Minimum="0" Maximum="255" />
</StackPanel>
Now, this beeing a MVVM app, I'd like to use Commands for this. However I can't see to find a way to send a Command without having to assign it to each slider separately. I read a bit on "Routed Commands" but that didn't give me a solution either.
How can i accomplish this?
Upvotes: 0
Views: 94
Reputation: 69959
If you insist on using an ICommand
then you should wrap the Slider.ValueChanged
event using an Attached Property. You can find out how to do that in my answer to the What's the best way to pass event to ViewModel? question.
However, you really shouldn't need to use any ICommand
... surely you can just create a new Color
each time one of the data bound properties change in the view model? This example enables the user to change the colour without using any ICommand
s:
<StackPanel Grid.Row="0" Grid.Column="1">
<Slider Value="{Binding R}" Minimum="0" Maximum="255" />
<Slider Value="{Binding G}" Minimum="0" Maximum="255" />
<Slider Value="{Binding B}" Minimum="0" Maximum="255" />
<Rectangle HorizontalAlignment="Stretch" Height="100">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding Color}" />
</Rectangle.Fill>
</Rectangle>
</StackPanel>
In view model:
private byte r = 127, g = 127, b = 127;
public byte R
{
get { return r; }
set { r = value; Color = Color.FromArgb((byte)255, R, G, B); NotifyPropertyChanged("R"); }
}
public byte G
{
get { return g; }
set { g = value; Color = Color.FromArgb((byte)255, R, G, B); NotifyPropertyChanged("G"); }
}
public byte B
{
get { return b; }
set { b = value; Color = Color.FromArgb((byte)255, R, G, B); NotifyPropertyChanged("B"); }
}
private Color color = Colors.Black;
public Color Color
{
get { return color; }
set { color = value; NotifyPropertyChanged("Color"); }
}
Upvotes: 1