简体   繁体   中英

WPF change color of Rectangle Fill in code

Hey all I am new at WPF's and am in need of changing the color of a Rectangle fill in a WPF.

Currently I have this:

<Rectangle Fill="{Binding aColor}" RadiusY="5" RadiusX="5">
    <Rectangle.Effect>
        <DropShadowEffect ShadowDepth="0"/>
    </Rectangle.Effect>
</Rectangle>

I am not sure how to go about using that binding above within code.

Any help would be great!

Fill property is of type Brush , so you cant bind color directly,

Do something like this,

<Rectangle Width="100"
           Height="100">
    <Rectangle.Fill>
        <SolidColorBrush Color="{Binding color}"/>
    </Rectangle.Fill>
</Rectangle>

Otherway is you can implement your Color-To-Brush converter. Like this

Got it!

C#:

System.Drawing.Color c = ColorTranslator.FromHtml("#FFFFFF");
System.Windows.Media.Color color = System.Windows.Media.Color.FromRgb(c.R, c.G, c.B);
aColor.Color = color;

XAML:

<Rectangle RadiusY="5" RadiusX="5">
  <Rectangle.Fill>
     <SolidColorBrush x:Name="aColor"/>
  </Rectangle.Fill>
  <Rectangle.Effect>
     <DropShadowEffect ShadowDepth="0"/>
  </Rectangle.Effect>
</Rectangle>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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