Click here to Skip to main content
16,020,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
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:

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

XML
<Rectangle x:Name="MyRectangle" Fill="#FF1122AA" Width="100" Height="50">
Posted
Updated 1-Jan-24 22:43pm
v6
Comments
[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    
Thanks.
Edited.
I was a mistyping in here.

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

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

    <Rectangle Name="Rectangle"
               Grid.Row="1"
               Fill="Red" />
</Grid>
 
Share this answer
 
Comments
Sh.H. 5-Jan-24 10:34am    
@Graeme_Grant
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    
@Graeme_Grant
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" ).

https://stackoverflow.com/questions/1037477/how-can-i-define-and-use-a-variable-in-xaml-to-define-a-color[^]
 
Share this answer
 
v2
Comments
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