我有一个应用程序,我编写了自己的导航窗口(由于各种原因),内容托管在边框内。当我换掉内容时,我需要一种机制,一旦内容被渲染就通知我,所以我可以自动调整整个窗口的大小。
我需要一种将窗口大小调整为内容或给出最大大小的行为。自动调整大小后,用户应以任何方式调整窗口大小。
我正在使用:
this.MaxHeight = 700;
this.MaxWidth = 800;
this.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
this.SizeToContent = System.Windows.SizeToContent.Manual;
this.MaxWidth = double.PositiveInfinity;
this.MaxHeight = double.PositiveInfinity;
但由于渲染并不总是完成,所以这不会一直有效。
编辑:我写了这个示例,表明渲染的内容只被触发一次:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="525"
Height="350"
ContentRendered="Window_ContentRendered">
<StackPanel>
<Border x:Name="border"
Width="200"
Height="200"
BorderBrush="Cornsilk"
BorderThickness="1">
<Ellipse Width="40"
Height="20"
Fill="AliceBlue"
Stroke="Black" />
</Border>
<Button x:Name="btn"
Click="btn_Click"
Content="ClickMe" />
<TextBlock x:Name="txtRender" />
</StackPanel>
</Window>
代码背后:
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
int rendercount = 0;
Random rnd = new Random();
public MainWindow()
{
InitializeComponent();
}
private void Window_ContentRendered(object sender, EventArgs e)
{
rendercount++;
txtRender.Text = rendercount.ToString();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
Ellipse ell = new Ellipse();
ell.Width = rnd.Next(50, 100);
ell.Height = rnd.Next(10, 100);
ell.Stroke = Brushes.Black;
ell.StrokeThickness = 2;
border.Child = ell;
}
}
}
答案 0 :(得分:0)
只需删除边框上的尺寸,然后仅在this.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
InitializeComponent();
工作XAML:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
ContentRendered="Window_ContentRendered">
<StackPanel>
<Border x:Name="border"
BorderBrush="Cornsilk"
BorderThickness="1">
<Ellipse Width="40"
Height="20"
Fill="AliceBlue"
Stroke="Black" />
</Border>
<Button x:Name="btn"
Click="btn_Click"
Content="ClickMe" />
<TextBlock x:Name="txtRender" />
</StackPanel>
</Window>
背后的代码
public partial class MainWindow : Window
{
int rendercount = 0;
Random rnd = new Random();
public MainWindow()
{
InitializeComponent();
this.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
}
private void Window_ContentRendered(object sender, EventArgs e)
{
rendercount++;
txtRender.Text = rendercount.ToString();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
Ellipse ell = new Ellipse();
ell.Width = rnd.Next(50, 100);
ell.Height = rnd.Next(10, 100);
ell.Stroke = Brushes.Black;
ell.StrokeThickness = 2;
border.Child = ell;
}
}