0

我有 2 个 Silverlight 用户控件,需要并排放置在容器中。它们中的任何一个都可选地存在(可见),如果缺少一个,我希望剩下的一个占据容器的 100% 宽度。基本上有 4 种可能的状态:如果 2 个控件都不存在,则容器折叠。其他都是这样

到目前为止,我得到的最远的是使用带有两列的 Grid

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="*"/>
  </Grid.ColumnDefinitions>
  <userControls:LeftControl Grid.Column="0" ...></userControls:LeftControl>
  <userControls:RightControl Grid.Column="1" ...></userControls:RightControl>
</Grid>

这工作正常,除非缺少正确的控件。然后左侧不会伸展。

4

1 回答 1

1

我不认为 Silverlight 布局系统能够自行解决这个问题。

看看这样的事情是否能让你更接近你的答案。

标记:

<Grid x:Name="LayoutRoot" Background="White">
    <StackPanel Orientation="Vertical" Width="400" Height="200" Background="Fuchsia">
        <Grid x:Name="ContainerGrid" Height="100" Background="Green">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Border x:Name="LeftControl" Grid.Column="0" Background="Red" LayoutUpdated="LeftControl_LayoutUpdated"></Border>
            <Border x:Name="RightControl" Grid.Column="1" Background="Blue" LayoutUpdated="RightControl_LayoutUpdated"></Border>
        </Grid>
        <Button x:Name="ToggleLeft" Content="Toggle Left" Click="ToggleLeft_Click"></Button>
        <Button x:Name="ToggleRight" Content="Toggle Right" Click="ToggleRight_Click"></Button>
    </StackPanel>
</Grid>

后面的代码:

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void ToggleLeft_Click(object sender, RoutedEventArgs e)
    {
        LeftControl.Visibility = 
            LeftControl.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
    }

    private void ToggleRight_Click(object sender, RoutedEventArgs e)
    {
        RightControl.Visibility = 
            RightControl.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
    }

    private void LeftControl_LayoutUpdated(object sender, EventArgs e)
    {
        ContainerGrid.ColumnDefinitions[0].Width =
            ContainerGrid.Children.Any(
                x => (int)x.GetValue(Grid.ColumnProperty) == 0 && x.Visibility == Visibility.Visible)
                ? new GridLength(1, GridUnitType.Star)
                : GridLength.Auto;
    }

    private void RightControl_LayoutUpdated(object sender, EventArgs e)
    {
        ContainerGrid.ColumnDefinitions[1].Width =
            ContainerGrid.Children.Any(
                x => (int)x.GetValue(Grid.ColumnProperty) == 1 && x.Visibility == Visibility.Visible)
                ? new GridLength(1, GridUnitType.Star)
                : GridLength.Auto;
    }
}
于 2012-09-06T20:33:29.833 回答