0

我有一个带有选项卡式控件的窗口,其中包含每个选项卡中不同大小的控件。我在我的窗口中使用 SizeToContent="WidthAndHeight",但我想让它只放大窗口大小。

例如,如果我移动到“更大”选项卡,我希望我的控件自动调整其大小,但如果我随后返回“更小”选项卡,我不希望我的控件再次减小其大小。我宁愿不使用 MinWidth 和 MinHeight,因为我希望我的用户能够手动减小窗口大小。

谢谢

4

1 回答 1

0

这是一个工作示例;

Xaml:

<Window x:Class="WpfApplicationUpper.Window3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window3" Height="300" Width="300" SizeToContent="WidthAndHeight">
<Grid>
    <TabControl Name="MainTabControl" 
                SelectionChanged="MainTabControl_SelectionChanged" 
                PreviewMouseDown="MainTabControl_PreviewMouseDown">
        <TabItem Header="Small Tab" >
            <Border Background="AliceBlue" Width="200" Height="200" />
        </TabItem>
        <TabItem Header="Medium Tab">
            <Border Background="Blue" Width="400" Height="400" />
        </TabItem>
        <TabItem Header="Large Tab">
            <Border Background="Navy" Width="600" Height="600" />
        </TabItem>
    </TabControl>
</Grid>
</Window>

后面的代码:

  public partial class Window3 : Window
  {
    public Window3() {InitializeComponent();}
    double _currentWidth;
    double _currentHeight;
    private void MainTabControl_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        TabItem currentItem = MainTabControl.SelectedItem as TabItem;
        FrameworkElement content = currentItem.Content as FrameworkElement;
        _currentWidth = content.ActualWidth;
        _currentHeight = content.ActualHeight;
    }
    private void MainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        TabItem itemAdded = null;
        TabItem itemRemoved = null;
        if (e.AddedItems.Count > 0)
            itemAdded = e.AddedItems[0] as TabItem;
        if (e.RemovedItems.Count > 0)
            itemRemoved = e.RemovedItems[0] as TabItem;

        if (itemAdded != null && itemRemoved != null)
        {
            FrameworkElement content = itemAdded.Content as FrameworkElement;
            double newWidth = content.Width;
            double newHeight = content.Height;
            if (newWidth < _currentWidth)
                content.Width = _currentWidth;
            if (newHeight < _currentHeight)
                content.Height = _currentHeight;
        }
    }
}

我知道这有点难看,但最好什么都不做:)

于 2012-12-29T17:13:28.527 回答