Mark A
Mark A

Reputation: 285

Fill color from property via XAML

I am learning WPF and have this simple question.
How do I set fill color to property vi XAML?

<Rectangle Fill="{Binding Path=BackgroundColorf}" 
           Height="112" Margin="0,84,0,0" VerticalAlignment="Top" 
           Width="116"/>
public partial class MainWindow : Window
{

         /// <summary>
        /// Gets or sets the BackgroundColor.  
        /// </summary>
   public SolidColorBrush BackgroundColorf
   {
       get;
       set;
   }

   public MainWindow()
   {
       this.InitializeComponent();
       BackgroundColorf =  new SolidColorBrush(Colors.Red); 
   }
}

Upvotes: 0

Views: 4200

Answers (3)

PaulB
PaulB

Reputation: 24422

To get you going ...

Add a name to Rectangle

<Rectangle x:Name="MyRect" Fill="{Binding Path=BackgroundColorf}" Height="112" ...

then in the code

 InitializeComponent();
 MyRect.DataContext = this;
 BackgroundColorf = new SolidColorBrush(Colors.Red);

Not the best way of doing things - but at least you'll have a red rectangle :)

Upvotes: 1

biju
biju

Reputation: 18040

Set the datacontext like this

public MainWindow()
   {
       this.DataContext = this;      
       this.InitializeComponent();
       BackgroundColorf =  new SolidColorBrush(Colors.Red); 
   }

This should work.But there is little more to be done for making your wpf app scalable like Notifications,Dependency properties etc.I recommend you go through the basics of wpf DataBinding architecture before continuing.Go through the link posted by H.B in the comments

Upvotes: 1

blindmeis
blindmeis

Reputation: 22445

if you add this your example will work

public MainWindow()
{
   this.InitializeComponent();
   this.DataContext =  this;
   BackgroundColorf =  new SolidColorBrush(Colors.Red); 
}

but you should really in some wpf books or websites to get the basics.

a very good Book is "WPF 4 Unleashed" from Adam Nathan.

Upvotes: 0

Related Questions