在主窗口中动态调整画布大小?

时间:2013-08-20 18:14:16

标签: wpf xaml wpf-controls

我一直坚持要在WPF中完成一个项目,而且我在WPF中唯一的经验就是从我开始以来过去一周从互联网上获得的(主要是SO)。因此,如果我的问题看起来很简单,或者即使是一个愚蠢的机智,答案似乎也很明显,那么我只能道歉并请求你的耐心!

这是构成我的主窗口的XAML:

<Window>
  <Grid Width="Auto" Height="Auto">
    <StackPanel>
      <DockPanel Margin="2">
        <StackPanel Orientation="Horizontal">
          <Border Name="leftPane" Height="Auto"  CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" Padding="8">
            <!-- Various controls here for the "left pane" -->
          </Border>
          <Separator BorderThickness="1" Margin="2"></Separator>
          <Border Name="rightPane" Height="Auto" CornerRadius="6" BorderBrush="Gray" BorderThickness="2" Padding="0" Background="#FFF0F0F0">
            <Canvas Name="canvasMain" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="Auto" Height="Auto">
                <!-- I need to resize the rightPane and the canvasMain when the user manually resizes the main window -->
            </Canvas>
          </Border>
        </StackPanel>
      </DockPanel>
    </StackPanel>
  </Grid>
</Window>

窗口或多或少看起来像这样:

=================================================================
-                                                               -
-  -------------   -------------------------------------------- -
-  | Left Pane |   |  Right Pane                              | -
-  | width:100 |   |  Need to expand width and height when    | -
-  |           |   |  ...the main window is resized by the    | -
-  |           |   |  ...user                                 | -
-  |           |   |                                          | -
-  |           |   |                                          | -
-  |           |   |                                          | -
-  |           |   |                                          | -
-  -------------   -------------------------------------------- -
=================================================================

我的第一个倾向是在主窗口的SizeChanged事件中简单地实现一些逻辑。但经过一段时间的谷歌搜索,我遇到了关于附加行为和属性触发器和事件触发器的主题,这反过来让我想到也许SizeChanged事件不是最好的路线。

因此,简而言之,动态调整窗口内容大小的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

您使用的是错误的容器,这就是您的用户界面无法自动调整大小的原因。

删除Grid(因为它是多余的)和StackPanel(因为它不适合您需要的布局容器。)

<Window>
  <DockPanel Margin="2">
      <StackPanel Orientation="Horizontal" DockPanel.Dock="Left" Width="100">
          <!-- Various controls here for the "left pane" -->
      </StackPanel>

      <Border>
          <Canvas/>
      </Border>
   </DockPanel>
</Window>

您永远不会为WPF中的任何内容处理SizeChanged事件。实际上,由于它具有高级的DataBinding功能和对解决方案无关性的本机支持,因此在WPF中可能习惯使用的大多数事件处理在WPF中都是无用的和不需要的。

相关问题