0
我想知道如何在調整大小時保持WPF窗口的寬高比(即:16x9) - 如果可能的話,可以利用MVVM。由於我是MVVM和WPF的新手,我不確定從哪裏開始。謝謝。WPF窗口長寬比
我想知道如何在調整大小時保持WPF窗口的寬高比(即:16x9) - 如果可能的話,可以利用MVVM。由於我是MVVM和WPF的新手,我不確定從哪裏開始。謝謝。WPF窗口長寬比
這可能很難用「純粹的」MVVM實現,因爲您需要知道調整大小發生的方向(水平或垂直)。請注意,如果兩者都一次更改(即用戶通過拖動角來調整大小),則需要決定使用哪些。
在你的ViewModel中,你可能會有一個名爲AspectRatio的屬性。
在您的視圖中,您很可能會覆蓋OnRenderSizeChanged事件。無論您是使用ViewModel中的屬性來完成視圖中的工作,還是將值傳遞給ViewModel中的某個屬性來完成工作,並將其綁定到新值,它都是一種品味問題。
例1:在這裏做的工作
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
if (sizeInfo.WidthChanged)
{
this.Width = sizeInfo.NewSize.Height * mViewModel.AspectRatio;
}
else
{
this.Height = sizeInfo.NewSize.Width * mViewModel.AspectRatio;
}
}
例2:不要在視圖模型
View.xaml.cs
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
if (sizeInfo.WidthChanged)
{
viewModel.AspectWidth = sizeInfo.NewSize.Width;
}
else
{
viewModel.AspectHeight = sizeInfo.NewSize.Height;
}
}
ViewModel.cs
public Double AspectWidth
{
get { return mAspectWidth; }
set
{
// Some method that sets your property and implements INotifyPropertyChanged
SetValue("AspectWidth", ref mAspectWidth, value);
SetValue("AspectHeight", ref mAspectHeight, mAspectWidth * mAspectRatio);
}
}
public Double AspectHeight
{
get { return mAspectHeight; }
set
{
// Some method that sets your property and implements INotifyPropertyChanged
SetValue("AspectHeight", ref mAspectHeight, value);
SetValue("AspectWidth", ref mAspectWidth, mAspectHeight* mAspectRatio);
}
}
而且你的觀點(例如2)的工作將結合窗口寬度和高度與視圖模型中的AspectWidth和AspectHeight屬性相關聯。
View.xaml
<Window Width="{Binding AspectWidth}"
Height="{Binding AspectHeight}">
</Window>
因此,在任何情況下,您都會覆蓋OnRenderSizeChanged。有關如何實施該方法的詳細信息取決於您的口味。我猜這個例子#2更接近於純粹的「MVVM」,但在這種情況下它也可能是矯枉過正的。