简体   繁体   中英

Calculating the padding of a XAML element as a percentage of its width

I'm trying to set the left and right padding of a textbox element in a XAML C# Windows Runtime app to be a percentage (10%) of the same element's width, so that when the element is resized along with the window, the padding changes to compensate. What is the best way to do this?

I've tried to do this by making a custom template for the textbox element and putting a grid with the correct column definitions inside the ScrollViewer along with a new ContentPresenter element. For some reason that I can't understand, however, moving the name attribute of the ScrollViewer to the newly created ContentPresenter causes a significant loss of performance. I would prefer if possible to use the default template if there is a better way of doing this.

Thanks in advance for any suggestions.

You could just create a ValueConverter that takes in the element that you want to match your width to. Then in your Textbox, you would bind your padding to the element, using the ValueConverter.

Something like this:

public sealed class PercentageOfValueConverter : IValueConverter
{
    private const double DefaultValue = 150;
    private const double Percentage = 0.9;

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        double result = 0;
        double.TryParse(value.ToString(), out result);

        if (result == double.NaN)
        {
            return DefaultValue; // Default value.
        }

        // Thickness gets assigned to the Padding property.
        return new Thickness(result * Percentage, 0, result * Percentage, 0);
    }

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

Then you would use the converter by binding the padding of your text box to it. The converter is provided the Binding Path, which in this case, is the Grid.Width property. We can take that and return back 90% of that value as a Thickness object, which is then assigned to the padding property.

<Grid x:Name="LayoutRoot">
    <Grid.Resources>
        <local:PercentageOfValueConverter x:Key="PercentageOfValueConverter" />
    </Grid.Resources>

    <TextBox Padding="{Binding ElementName=LayoutRoot, 
                    Converter={StaticResource PercentageOfValueConverter}, 
                    Path=Width, Mode=TwoWay, 
                    UpdateSourceTrigger=PropertyChanged}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM