Personally, I would try to arrange my layouts better so that they do not depend on the size of the switches. However, if you absolutely insist on doing it this way, you will need to set the width of each TextBlock according to its size when Bold, and in such a way that it will update it if you need to change the text and / or font family, etc. To do this, you need to bind the Width property to a converter that takes all these other values.
Start with a style that sets the width of the text box:
<Style TargetType="{x:Type TextBlock}"> <Setter Property="Width"> <Setter.Value> <MultiBinding Converter="{StaticResource TextToWidthConverter}"> <Binding Path="Text" RelativeSource="{RelativeSource Self}" UpdateSourceTrigger="PropertyChanged"/> <Binding Path="FontFamily" RelativeSource="{RelativeSource Self}" UpdateSourceTrigger="PropertyChanged"/> <Binding Path="FontStyle" RelativeSource="{RelativeSource Self}" UpdateSourceTrigger="PropertyChanged"/> <Binding Path="FontStretch" RelativeSource="{RelativeSource Self}" UpdateSourceTrigger="PropertyChanged"/> <Binding Path="FontSize" RelativeSource="{RelativeSource Self}" UpdateSourceTrigger="PropertyChanged"/> </MultiBinding> </Setter.Value> </Setter> </Style>
Now add the code for the value converter itself (note that I'm using fooobar.com/questions/100732 / ... to measure text):
public class TextToWidthConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var text = values[0] as String; var fontFamily = values[1] as FontFamily; var fontStyle = (FontStyle)values[2]; var fontStretch = (FontStretch)values[3]; var fontSize = (Double)values[4]; var size = MeasureText(text, fontFamily, fontStyle, FontWeights.Bold, fontStretch, fontSize); return size.Width; } public object[] ConvertBack(object values, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); }
But then again, in a real application, I will try to solve it correctly by putting them in a grid or something like that.
source share