Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind width of popup to width of other control with some margin

Tags:

wpf

I want my popup to have the same width as the width of another control, but with some margin.

What I want is

 <Popup x:Name="ProfilePopup" Height="Auto"   
      Width="{Binding ActualWidth, ElementName=HeaderContainer}" -10 >

But how do you do the '-10' part in wpf ? or is this only possible in code?

like image 791
Robby Smet Avatar asked Mar 22 '23 03:03

Robby Smet


2 Answers

Converter,

or trick:

<Popup x:Name="ProfilePopup" AllowsTransparency="True" Height="Auto" Width="{Binding ActualWidth, ElementName=HeaderContainer}" >
    <Grid Margin="5,0" />
</Popup>
like image 179
dovid Avatar answered Mar 24 '23 18:03

dovid


You'll need a Converter to do this for you:

public class SumConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter != null && values != null)
        {
            double result = 0;
            foreach (object objectValue in values)
            {
                double value = 0;
                double.TryParse(objectValue.ToString(), out value);
                if (parameter.ToString() == "Add" || parameter.ToString() == "+") 
                    result += value;
                if (parameter.ToString() == "Subtract" || parameter.ToString() == "-") 
                    result -= value;
            }
            return result;
        }
        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return null;
    }
}

You'd need to add a property containing the amount that you want to subtract (named BorderInnerThickness in the example) and then you would use it like this:

<Popup x:Name="ProfilePopup" Height="Auto">
    <Popup.Width>
        <MultiBinding Converter="{StaticResource SumConverter}" ConverterParameter="-">
            <Binding Path="ActualWidth" ElementName="HeaderContainer" />
            <Binding Path="BorderInnerThickness" />
        </MultiBinding>
    </Popup.Width>
</Popup>
like image 21
Sheridan Avatar answered Mar 24 '23 19:03

Sheridan