繁体   English   中英

将MVVM命令绑定到UWP中的TimePicker控件

[英]Binding MVVM Command to TimePicker control in UWP

我在XAML页面上使用TimePicker控件,并尝试对相应ViewModel更改做出反应。 我在Xaml.Interactivity添加了Xaml.InteractivityXaml.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 ViewModelBaseDelegateCommand

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使用BindingViewModelCommand连接,而是使用编译后的绑定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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM