I have a series of TextBlock
and TextBox
controls. Is there a way to apply a Style
to the TextBlock
s such that they can
I know this is an old thread, but I've found a solution to this problem. I was able to use Aland Li's suggestion, found here. Its not quite as generic as it is in CSS, but if you know the parent element type, this works nicely even in a Style.
Here's an example of how I used it. I have a TextBox control that lights up with a "highlight color" when it has focus. Additionally, I wanted its associated Label control to also light up when the TextBox had focus. So I wrote a Trigger for the Label control that made it light up in a similar way that the TextBox control did. This Trigger is triggered by a custom attached property called IsFocusedByProxy. Then I needed to bind the Label's IsFocusedByProxy to the TextBox's IsFocused. So I used this technique:
<Grid x:Name="MaxGrid">
<Label x:Name="MaxLabel"
Content="Max:"
c5:TagHelper.IsFocusedByProxy="{Binding
Path=Children[1].IsFocused,
RelativeSource={RelativeSource AncestorType=Grid}}"
/>
<c5:TextBoxC5Mediator x:Name="MaxTextBox"
DataContext="{Binding ConfigVm.Max_mediator}" />
</Grid>
At this point you may be thinking that its not any better than than just using ElementName in the Binding. But the difference is that now I can move this binding into a Style for reusability:
<Setter Property="C5_Behaviors:TagHelper.IsFocusedByProxy"
Value="{Binding Path=Children[1].IsFocused,
RelativeSource={RelativeSource AncestorType=Grid}}" />
And now I can when I have a View full of these occurances, like this (I have setup the necessary Styles to be applied implicitly, so that's why there's no markup shown that sets the Styles):
<Grid x:Name="MaxGrid">
<Label x:Name="MaxLabel"
Content="Max:" />
<c5:TextBoxC5Mediator x:Name="MaxTextBox"
DataContext="{Binding ConfigVm.Max_mediator}" />
</Grid>
<Grid x:Name="MinGrid">
<Label x:Name="MinLabel"
Content="Min:" />
<c5:TextBoxC5Mediator x:Name="MinTextBox"
DataContext="{Binding ConfigVm.Min_mediator}" />
</Grid>
<Grid x:Name="StepFactorGrid">
<Label x:Name="StepFactorLabel"
Content="Step Factor:" />
<c5:TextBoxC5Mediator x:Name="StepFactorTextBox"
DataContext="{Binding ConfigVm.StepFactor_mediator}" />
</Grid>
<!-- ... and lots more ... -->
Which gives me these results:
Before any TextBoxes have focus:
With different TextBoxes receiving focus:
I think the best thing to do in this case is bind by ElementName:
<TextBlock Text="{Binding ElementName=textBox1, Path=Text}" />
<TextBox x:Name="textBox1">this is the textBox's 1 text</TextBox>
<TextBlock Text="{Binding ElementName=textBox2, Path=Text}" />
<TextBox x:Name="textBox2">this is the textBox's 2 text</TextBox>
It will achieve something similar. Does this work for you?