Reputation: 61
I am creating a Windows Phone 8 app that has a grid of rectangles. Each of the rectangles starts at a particular color using the fill property. I want to be able to change the color of the rectangle by tapping on it, however, I am unable to find a way to modify the fill property from my c# code side. Is there a way to make this possible? I have seen lots of information about the Brush class, but it does not seem to be supported on windows phone 8.
Example of xaml.
<Rectangle x:Name="mon9a" Fill="#FFD69F50" HorizontalAlignment="Left" Height="48" Margin="58,94,0,0" Stroke="Black" VerticalAlignment="Top" Width="73" Tap="mon9a_Tapped"/>
Upvotes: 1
Views: 1446
Reputation: 5871
The best way to achieve this would be to create a ViewModel for your page and bind the rectangle Fill property to a property there.
E.g.
<Rectangle x:Name="mon9a" Fill="{Binding MyFillProperty, Mode=OneWay}" HorizontalAlignment="Left" Height="48" Margin="58,94,0,0" Stroke="Black" VerticalAlignment="Top" Width="73" Tap="mon9a_Tapped"/>
You either need a property for each rectangle in your ViewModel, or a bit more elegantly you'd have a collection of rectangles in your page's ViewModel that you are binding to in order to render your rectangles on the page (so you don't need to add each on manually). Each of these rectangle objects in your collection will also be a ViewModel object that raises the appropriate Property Changed events so your XAML automatically updates itself with any changes to the Fill color property when set on the tap event.
ViewModels are well worth the effort in learning about in Windows Phone as they'll make life a lot easier by removing a lot of manual code plumbing and will keep your code cleaner.
Upvotes: 0
Reputation: 1360
Something like this should do the trick. Obviously you need to set the colour of the solidcolourbrush to your desired colour.
private void rectangle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
// Change this colour to whatever colour you want.
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 255, 255, 0);
System.Windows.Shapes.Rectangle rect = (System.Windows.Shapes.Rectangle)sender;
rect.Fill = mySolidColorBrush;
}
Upvotes: 1