简体   繁体   English

更改矩形Windows Phone 8的颜色

[英]Change the Color of a Rectangle Windows Phone 8

I am creating a Windows Phone 8 app that has a grid of rectangles. 我正在创建具有矩形网格的Windows Phone 8应用程序。 Each of the rectangles starts at a particular color using the fill property. 每个矩形都使用fill属性以一种特定的颜色开始。 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. 我希望能够通过点击它来更改矩形的颜色,但是,我找不到从C#代码端修改fill属性的方法。 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. 我已经看到了许多有关Brush类的信息,但Windows Phone 8似乎不支持它。

Example of xaml. 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"/>

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;
    }

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. 实现此目的的最佳方法是为页面创建ViewModel并将矩形Fill属性绑定到该属性。

Eg 例如

<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). 您要么为ViewModel中的每个矩形都需要一个属性,要么更优雅一些,您要绑定到页面的ViewModel中有一个矩形集合,以便在页面上呈现矩形(因此,您不需要以手动添加每个)。 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. 集合中的每个矩形对象都将是一个ViewModel对象,该对象将引发相应的Property Changed事件,因此,在对tap事件进行设置时,您的XAML会使用对Fill color属性的任何更改自动更新自身。

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. ViewModel非常值得在Windows Phone中进行学习,因为它们可以消除大量手动代码管道,从而使工作变得更加轻松,并使您的代码更整洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM