我有一个简单的MVVM模式,我有一个ViewModel和View(在这种情况下只有两个问题):
视图模型:
public class LoginWindowViewModel : Bases.ViewModelBase
{
private double _width = 400;
public double Width
{
get { return _width; }
set { SetProperty(ref _width, value); }
}
private double _height = 500;
public double Height
{
get { return _height; }
set { SetProperty(ref _height, value); }
}
private BitmapImage _backgroundImage = null;
public BitmapImage BackgroundImage
{
get
{
if (_backgroundImage == null) _backgroundImage = Model.Imagining.GetRandomImage((int)Width, (int)Height);
return _backgroundImage;
}
}
}
查看:
public partial class LoginWindow : Window
{
public LoginWindowViewModel ViewModel
{
get { return (LoginWindowViewModel)DataContext; }
}
public LoginWindow()
{
InitializeComponent();
}
private void mainWindow_Loaded(object sender, RoutedEventArgs e)
{
Open();
}
public void Open()
{
Open(Settings.Default.AnimationDuration);
}
public void Open(Duration animDuration)
{
UpdateLayout();
mainWindow.Clip = new EllipseGeometry(new Point(mainWindow.Width / 2, mainWindow.Height / 2), 0, 0);
double radius = MathFunctions.CalculatePitagoras(mainWindow.Width, mainWindow.Height) / 2;
Animations.RadiusXAnimation((EllipseGeometry)mainWindow.Clip, radius, animDuration);
Animations.RadiusYAnimation((EllipseGeometry)mainWindow.Clip, radius, animDuration);
}
}
查看XAML:
<Window x:Name="mainWindow" x:Class="Gestionale.View.LoginWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Gestionale.View"
xmlns:viewModels="clr-namespace:Gestionale.ViewModel"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
Style="{DynamicResource MaterialDesignCardWindow}"
Background="{x:Null}"
Title="LoginWindow" WindowStartupLocation="CenterScreen" ResizeMode="NoResize"
Width="{Binding Width, Mode=TwoWay}"
Height="{Binding Height, Mode=TwoWay}"
Loaded="mainWindow_Loaded">
<Window.DataContext>
<viewModels:LoginWindowViewModel />
</Window.DataContext>
<Grid x:Name="mainGrid">
<Image Source="{Binding BackgroundImage}" Margin="-1" />
<Rectangle Fill="{DynamicResource PrimaryHueMidBrush}" />
<Grid>
...
</Grid>
</Grid>
</Window>
正如您所看到的,我在ViewModel和View之间建立了一个简单的绑定,其中Height和Width在ViewModel中设置,其原因是当我获得从Internet下载的Image时,它会自动绑定到视图的图像。我想在Window加载后立即执行开始动画,如下所示:
public MainWindow()
{
if(LoggedUser == null)
{
LoginWindow newLoginWindow = new LoginWindow();
newLoginWindow.ShowDialog();
}
InitializeComponent();
}
但我的确切问题是,当我调用Loaded事件时,其中一个值(Width或Height,它取决于它在XAML中绑定的位置)是不同的,并且它在Loaded标注之后发生了变化,我通过在SizeChanged事件(不在这里)上创建一个断点来检查。 基本上(在这种情况下)它是这样的: 初始化(宽度:随机,高度:随机) - &gt;宽度:400高度:随机(在我的情况下每次由于某种原因为749) - &gt;已加载 - &gt;宽度:400高度:500
如果我将XAML中的绑定位置反转为高度优先和宽度秒,则情况相同但高度正确且加载后宽度正在更改。这对我来说是一个很大的问题,因为我尝试制作一个正确的动画但是我的中心点是不同的。