[英]Binding MVVM Command to TimePicker control in UWP
我在XAML页面上使用TimePicker
控件,并尝试对相应ViewModel
更改做出反应。 我在Xaml.Interactivity
添加了Xaml.Interactivity
和Xaml.Interactivity.Core
命名空间,以便在调用TimeChanged
事件后使用Behaviors SDK
来触发命令。
<!-- 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的讨论。 我找到了解决我的问题的方法。 现在,我ViewModel
使用Binding
与ViewModel
的Command
连接,而是使用编译后的绑定x:Bind
直接将事件与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;
}
引用此链接
EventTriggerBehavior不支持TimeChanged事件。 支持的事件是
Tapped
PointerPressed
Loaded
DataContextChanged
Click
Checked
Unchecked
SelectionChanged
TextChanged
Toggled
NavigationCompleted
您必须实现自定义行为以支持TimeChanged事件
这是实现自定义行为的链接Implement_custom_behaviour
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.