这是WPF/MVVM应用程序。MainWindow.xaml.cs后面的代码中有一些代码应该生成自定义事件,并且需要向视图模型类(MainWindowViewModel.cs(报告此事件的事实(可能带有args(。
例如,我在分部类MainWindow中声明了RoutedEvent TimerEvent,但由于此事件在xaml代码中不可用,我无法绑定到视图模型命令。错误:计时器无法识别或无法访问。
如何解决这个问题?谢谢
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var timer = new Timer();
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Interval = 5000;
timer.Enabled = true;
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
RaiseTimerEvent();
}
// Create a custom routed event
public static readonly RoutedEvent TimerEvent = EventManager.RegisterRoutedEvent(
"Timer", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MainWindow));
// Provide CLR accessors for the event
public event RoutedEventHandler Timer
{
add => AddHandler(TimerEvent, value);
remove => RemoveHandler(TimerEvent, value);
}
void RaiseTimerEvent()
{
var newEventArgs = new RoutedEventArgs(MainWindow.TimerEvent);
RaiseEvent(newEventArgs);
}
}
<Window x:Class="CustomWindowEvent.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomWindowEvent"
Title="MainWindow" Height="250" Width="400"
Timer="{Binding TimerCommand}"> // THIS PRODUCE ERROR Timer is not recognized or is not accessible.
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<StackPanel>
<TextBlock Text="{Binding Title}"/>
<Button Width="75"
Height="24"
Content="Run"
Command="{Binding RunCommand}"/>
</StackPanel>
</Grid>
</Window>
不能像那样将ICommand
属性绑定到事件。
当您的窗口发出命令时,您可以通过编程方式调用该命令:
void RaiseTimerEvent()
{
var newEventArgs = new RoutedEventArgs(MainWindow.TimerEvent);
RaiseEvent(newEventArgs);
var vm = this.DataContext as MainWindowViewModel;
if (vm != null)
vm.TimerCommand.Execute(null);
}
另一种选择是使用Microsoft的EventTrigger
和InvokeCommandAction
。Xaml。行为。使用XAML调用命令的Wpf包:
<Window .. xmlns:i="http://schemas.microsoft.com/xaml/behaviors">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Timer" >
<i:InvokeCommandAction Command="{Binding TimerCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Window>
请参阅此博客文章了解更多信息。