這是 WPF/MVVM 應用程式。MainWindow.xaml.cs后面的代碼中有一些代碼應該生成自定義事件,并且需要報告此事件的事實(可能帶有 args)以查看模型類 (MainWindowViewModel.cs)。
例如。我在部分類 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>
uj5u.com熱心網友回復:
您不能像那樣將ICommand屬性系結到事件。
當您的視窗發出命令時,您可以以編程方式呼叫該命令:
void RaiseTimerEvent()
{
var newEventArgs = new RoutedEventArgs(MainWindow.TimerEvent);
RaiseEvent(newEventArgs);
var vm = this.DataContext as MainWindowViewModel;
if (vm != null)
vm.TimerCommand.Execute(null);
}
另一種選擇是使用一個EventTrigger和InvokeCommandAction從Microsoft.Xaml.Behaviors.Wpf包來呼叫使用XAML命令:
<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>
請參閱此博客文章了解更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/357659.html
