我一直在尝试实现菜单更改到另一个菜单之间的转换。我正在使用 WPF .Net 8 和 Caliburn Micro 进行 MVVM。
所以我在 MainView.xaml 中创建了名为 MenuChangeStart 的故事板动画。在我的 MainViewModel.cs 中,我有一个方法,当用户单击主页按钮时调用。现在我想在更改菜单之前启动此动画。
public void ActivateHomeView()
{
CurrentMenuIcon = @"\Resources\home.png";
//the MenuChangeStart animation goes here
ActivateItemAsync(new HomeViewModel());
}
我尝试用两种方式做到这一点,但我都遇到了问题。
所以最初我尝试在 MainViewModel.cs 中使用这段代码,但我发现其中不存在
FindResource
。
//MainViewModel.cs
public void MenuChangeOpen()
{
Storyboard sb = this.FindResource("MenuChangeStart") as Storyboard;
sb.Begin();
}
然后我可以从
MenuChangeOpen()
称之为
ActivateHomeView()
我将此
MenuChangeOpen()
方法移至 MainView.xaml.cs,然后从 ViewModel 调用它,但我找不到正确调用它的方法。我使用了下面提到的代码,但它抛出一个错误,说 _view 为空。
//MainViewModel.cs
private MainView _view;
public MainViewModel(MainView view) => _view = view;
//InHome menu change
public void ActivateHomeView()
{
//the _view seems to be null
CurrentMenuIcon = @"\Resources\home.png";
if(_view != null)
{
_view.MenuChangeOpen();
}
ActivateItemAsync(new HomeViewModel());
}
在 XAML 中使用 EventTrigger 以及 Microsoft.Xaml.Behaviors.Wpf NuGet 包中的 EventTriggerBehavior。
private RelayCommand _startAnimationCommand;
public RelayCommand StartAnimationCommand
{
get
{
return _startAnimationCommand ?? (_startAnimationCommand = new RelayCommand(param => StartAnimation()));
}
}
在xaml中:添加
<Window.Resources>
<Storyboard x:Key="YourAnimationStoryboard">
<!-- Define your animation here -->
</Storyboard>
</Window.Resources>
<Grid>
<Button Content="Start Animation">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding StartAnimationCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>