Click here to Skip to main content
15,905,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to change the color of text in TextBlock equal to color of Rectangle in another part of the Grid.
With respect, any kindly Help please?

What I have tried:

<TextBlock Grid.Row="0" Grid.Column="0" Text="Helllllo!" Foreground="{Binding Fill, ElementName=MyRectangle}">

<Rectangle x:Name="MyRectangle" Fill="#FF1122AA" Width="100" Height="50">
Updated 1-Jan-24 22:43pm
[no name] 1-Jan-24 16:29pm    
You're missing a closing "}" in your binding for one thing.
Sh.H. 2-Jan-24 4:22am    
I was a mistyping in here.

If it is not working, then you need to point to the property using Path:
        <RowDefinition />
        <RowDefinition />

    <TextBlock Foreground="{Binding ElementName=Rectangle, Path=Fill}"
               Text="MyText" />

    <Rectangle Name="Rectangle"
               Fill="Red" />
Share this answer
Sh.H. 5-Jan-24 10:34am    
Unfortunately doesn't work.
Graeme_Grant 5-Jan-24 17:12pm    
Sorry? The code was tested before posting. Works 100%.
Sh.H. 5-Jan-24 17:36pm    
Yes. I don't know why doesn't work on my system.
I wish I could send here a video of my screen, so you could see that it doesn't work here.
Graeme_Grant 5-Jan-24 17:49pm    
Seriously? The code was tested before posting. Create a new project, copy and paste the code and run it. Here is a screenshot of it running, and code used: Wpf Bind To Control Color - Imagebin[^]
[no name] 4-Feb-24 20:40pm    
The question pertains to the scenario where a TextBlock and a Rectangle are originally placed in different grids, The concern raised is regarding how these elements will interact, considering they are not initially part of the same visual tree.
Your approach to coloring the rectangle appears to be wrong in the first place (HTML vs XAML). Use a static resource as illustrated here since you need the same color in more than one place anyway. (Otherwise you'd use a Rectangle.Fill "object" ).[^]
Share this answer
Sh.H. 2-Jan-24 16:39pm    
@Gerry Schmitz
Thanks. The color of Rectangle works fine. What I need is changing color of TextBlock base on the color of Rectangle.
The link you sent is not good answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900