最簡單的辦法是使用視框,但它也可以很簡單地計算Window調整大小的比例。
視框
<Window x:Class="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">
<Viewbox Stretch="Uniform">
<Grid>
<Label>
Hello world
</Label>
</Grid>
</Viewbox>
</Window>
手動縮放
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Name="myMainWindow"
Width="200" Height="250">
<Grid Name="MainGrid" SizeChanged="MainGrid_SizeChanged">
<Grid.LayoutTransform>
<ScaleTransform x:Name="ApplicationScaleTransform"
CenterX="0"
CenterY="0"
ScaleX="{Binding ElementName=myMainWindow, Path=ScaleValue}"
ScaleY="{Binding ElementName=myMainWindow, Path=ScaleValue}" />
</Grid.LayoutTransform>
<Grid VerticalAlignment="Center" HorizontalAlignment="Center" Height="150">
<TextBlock FontSize="20" Text="Hello World" Margin="5" VerticalAlignment="Top" HorizontalAlignment="Center"/>
<Button Content="Button" VerticalAlignment="Bottom" HorizontalAlignment="Center"/>
</Grid>
</Grid>
其中網格是使用通過參考是一個編碼ScaleValue依賴屬性確定的ScaleX & scaleY屬性一個LayoutTransform縮放在Window_Resize事件期間使用類似於
的代碼計算
#region ScaleValue Dependency Property
public static readonly DependencyProperty ScaleValueProperty = DependencyProperty.Register("ScaleValue", typeof(double), typeof(MainWindow), new UIPropertyMetadata(1.0, new PropertyChangedCallback(OnScaleValueChanged), new CoerceValueCallback(OnCoerceScaleValue)));
private static object OnCoerceScaleValue(DependencyObject o, object value)
{
MainWindow mainWindow = o as MainWindow;
if (mainWindow != null)
return mainWindow.OnCoerceScaleValue((double)value);
else
return value;
}
private static void OnScaleValueChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
MainWindow mainWindow = o as MainWindow;
if (mainWindow != null)
mainWindow.OnScaleValueChanged((double)e.OldValue, (double)e.NewValue);
}
protected virtual double OnCoerceScaleValue(double value)
{
if (double.IsNaN(value))
return 1.0f;
value = Math.Max(0.1, value);
return value;
}
public double ScaleValue
{
get
{
return (double)GetValue(ScaleValueProperty);
}
set
{
SetValue(ScaleValueProperty, value);
}
}
#endregion
private void CalculateScale()
{
double yScale = ActualHeight/250f;
double xScale = ActualWidth/200f;
double value = Math.Min(xScale, yScale);
ScaleValue = (double)OnCoerceScaleValue(MainGrid, value);
}
什麼?這是WPF嗎?你並不需要那個。在這個問題中沒有足夠的信息來提供答案。請說明 –
是的,它是WPF,添加了標籤並希望添加足夠的。我需要的是在調整它的大小時動態調整我的應用程序的大小。 – Herrozerro
我不明白。 WPF本質上是獨立於分辨率的。你爲什麼要申請一個'ScaleTransform'? –