我有一个带有内置选项卡控件的窗口,其中包含每个选项卡中不同大小的控件。我在我的窗口中使用SizeToContent =“WidthAndHeight”,但我想允许它只放大窗口大小。例如,如果我移动到“更大”选项卡,我希望我的控件自动调整其大小,但如果我然后返回到“更小”选项卡,我不希望我的控件减少其大小大小再次。我宁愿不使用MinWidth和MinHeight,因为我希望我的用户能够手动减小窗口大小。允许SizeToContent放大但不缩小它
谢谢
我有一个带有内置选项卡控件的窗口,其中包含每个选项卡中不同大小的控件。我在我的窗口中使用SizeToContent =“WidthAndHeight”,但我想允许它只放大窗口大小。例如,如果我移动到“更大”选项卡,我希望我的控件自动调整其大小,但如果我然后返回到“更小”选项卡,我不希望我的控件减少其大小大小再次。我宁愿不使用MinWidth和MinHeight,因为我希望我的用户能够手动减小窗口大小。允许SizeToContent放大但不缩小它
谢谢
这是一个工作示例;
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;
}
}
}
我知道这是一个有点难看,但它是更好的,没有什么:)
感谢你的答案。这个解决方案并没有那么糟糕,但我想等待看看是否有一种“更清洁”的方法。我不喜欢,特别是,必须检查当前标签更改的时间,因为在尺寸应该改变时(例如当前标签的内容增加其大小时)可能存在其他情况。此外,我所有的控件都将“高度”和“宽度”设置为“自动”,因此我不认为使用“宽度”和“高度”属性有效。我想我必须使用ActualWidth和ActualHeight –
这可以给你一个想法:您应该处理宽度和高度属性更改的事件。如果他们将变得更大,请设置SizeToContent =“WidthAndHeight”,否则,应该尝试阻止这种情况的发生。 – Ramin
@Ramin谢谢你的建议。我认为SizeToContent应该是WidthAndHeight,不是吗?无论如何,拦截变化可能会奏效,但是我认为我必须将宽度和/或高度设置为旧值,并且AFAIK,SizeToContent不适用于固定的高度/宽度 –
我的意思是,如果大小正在变大要小一些,您应该将SizeToContent设置为手动,然后保留以前的大小。如果大小将变得更大,请将SizeToContent设置为WidthAndHeight。如果出现PropertyChanging事件,我认为它是笔直的(设置SizeToContent = Manual和取消宽度和高度变化,当它变小时),但我认为没有事件发生。所以,你可以处理Width和Height改变的事件。如果它们变大,只需设置SizeToContent = WidthAndHeight。如果它们变小了,请设置SizeToContent = Manual并将Height和Width设置为较大的那个。 – Ramin