我在 XAML 页面上使用 TimePicker 控件,并尝试对相应 ViewModel 中的更改使用react。我将 Xaml.Interactivity 和 Xaml.Interactivity.Core 命名空间添加到我的页面,以便使用 Behaviors SDK 在TimeChanged 事件被调用。
<!-- XAML Namespaces -->
xmlns:interact="using:Microsoft.Xaml.Interactivity"
xmlns:interactcore="using:Microsoft.Xaml.Interactions.Core"
<TimePicker x:Name="TestTimePicker" ClockIdentifier="24HourClock" Time="0">
<interact:Interaction.Behaviors>
<interactcore:EventTriggerBehavior EventName="TimeChanged">
<interactcore:InvokeCommandAction Command="{Binding DataContext.TimeChangedCommand}" CommandParameter="{Binding ElementName=TestTimePicker, Path=Time}" />
</interactcore:EventTriggerBehavior>
</interact:Interaction.Behaviors>
</TimePicker>
对于我的 ViewModel 中的代码,我使用 Template10 中的 ViewModelBase 和 DelegateCommand。
public DelegateCommand<TimeSpan> StartTimeChangedCommand { get; set; }
public TestViewModel()
{
...
TimeChangedCommand = new DelegateCommand<TimeSpan>(TimeChangedAction);
...
}
private void TimeChangedAction(TimeSpan obj)
{
//do something with obj
}
页面初始化后,将抛出包含以下消息的 InvalidOperationException。
Adding or removing event handlers dynamically is not supported on WinRT events.
请您参考如下方法:
感谢@Archana 的讨论。我找到了解决问题的方法。 我现在使用编译绑定(bind) x:Bind 来连接 ViewModel 中的 Command 而不是使用 Binding直接将事件与 ViewModel 中的处理程序连接。
我更新了 TimePicker 控件
<TimePicker x:Name="TestTimePicker" ClockIdentifier="24HourClock" Time="{x:Bind ViewModel.TestTime, Mode=TwoWay}" TimeChanged="{x:Bind ViewModel.TestTimeChangedEvent}" />
以及 ViewModel 中的代码
public void TestTimeChangedEvent (object sender, TimePickerValueChangedEventArgs e)
{
TestTime = e.NewTime;
}
