开发者

Binding from multiple element in wpf

开发者 https://www.devze.com 2023-01-04 08:52 出处:网络
I have 3 wpf control name \"A\" \"B\" \"C\". I want to bind C co开发者_StackOverflow社区ntrol height.

I have 3 wpf control name "A" "B" "C". I want to bind C co开发者_StackOverflow社区ntrol height.

Easy understand: C.Height=A.Height+B.Height

This is my dream. :)

< C >
 < C.Height >
  < SumBinding >
    < Binding ElementName=A, Path=Height/ >
    < Binding ElementName=B, Path=Height/ >
  < /SumBinding >
 < /C.Height >
< /C >

How to do it?

Is it possible to do not using converter?

Otherwise possible to create SumBinding like class?


You can bind a property to multiple bindings using a MultiBinding, although you will need to use a converter implementing IMultiValueConverter in order to use them. In this case, you will probably want to bind to Height rather than ActualHeight so that you get the value after layout is performed.

You would define a converter like this:

public class SumConverter
    : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.Cast<double>().Sum();
    }

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

And then do something like this in XAML:

<Control Name="C">
    <Control.Resources>
        <local:SumConverter x:Key="SumConverter"/>
    </Control.Resources>
    <Control.Height>
        <MultiBinding Converter="{StaticResource SumConverter}">
            <Binding Path="ActualHeight" ElementName="A" />
            <Binding Path="ActualHeight" ElementName="B" />
        </MultiBinding>
    </Control.Height>
</Control>

If you're just trying to get the height of controls to be in a fixed ratio with each other, you might want to use a Grid with star sizing or multiple grids with shared size groups. Something like this might work:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="2*"/>
    </Grid.RowDefinitions>
    <Button Grid.Row="0">A</Button>
    <Button Grid.Row="1">B</Button>
    <Button Grid.Row="2">C</Button>
</Grid>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号