I wish to have a set of elements have the same width, I can not simply put them in a grid as this is a content control and the elements being bound is unknown.
As a simple example, how do I bind all widths of the first child of each stack panel together along with the second element.
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="First column"/>
<Label Content="Second Column" Background="Green"/>
</Sta开发者_高级运维ckPanel>
<StackPanel Orientation="Horizontal">
<Label Content="One"/>
<Label Content="Two" Background="Green"/>
</StackPanel>
</StackPanel>
I'm not clear on your reason for not using a Grid from the sample code here but Grid gives you a built-in mechanism to do this:
<StackPanel Grid.IsSharedSizeScope="True">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Col1"/>
<ColumnDefinition Width="Auto" SharedSizeGroup="Col2"/>
</Grid.ColumnDefinitions>
<Label Content="First column" Grid.Column="0"/>
<Label Content="Second Column" Background="Green" Grid.Column="1"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="Col1"/>
<ColumnDefinition SharedSizeGroup="Col2"/>
</Grid.ColumnDefinitions>
<Label Content="One" Grid.Column="0"/>
<Label Content="Two" Background="Green" Grid.Column="1"/>
</Grid>
</StackPanel>
Will this work for you or do you have other constraints that won't allow you to do this?
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label x:Name="FirstColumnLabel" Content="First column"/>
<Label x:Name="SecondColumnLabel" Content="Second Column" Background="Green"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="One" Width="{Binding ElementName=FirstColumnLabel, Path=ActualWidth}"/>
<Label Content="Two" Width="{Binding ElementName=SecondColumnLabel, Path=ActualWidth}" Background="Green"/>
</StackPanel>
</StackPanel>
精彩评论