Mykhailo Seniutovych
Mykhailo Seniutovych

Reputation: 3711

How to pass ActualWidth of TextBox to Converter using TemplateBinding in WPF

I'm trying to pass ActualWidth of TextBox to Converter when binding using TemplateBinding. This is the XAML:

<Style x:Key="TextBoxStyle" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsKeyboardFocused, RelativeSource={RelativeSource Self}}" Value="false">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TextBox">
                        <TextBlock Text="{TemplateBinding Text}" Width="{TemplateBinding ActualWidth , Converter={StaticResource FullWidthToContentWidthConverter}, ConverterParameter='10'}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>

And this is the converter itself:

public class FullWidthToContentWidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var fullWidth = double.Parse(value.ToString());

        var widthToSubtract = double.Parse(parameter.ToString());

        return fullWidth - widthToSubtract;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Every time I run this app value that comes to FullWidthToContentWidthConverter.Convert is equal 0, which is not true. I also tried to replace ActualWidth with Width then value became equal to NaN, which is also not the case. How can I pass real ActualWidth?

Upvotes: 0

Views: 519

Answers (0)

Related Questions