【问题标题】:Can a WPF DataTrigger Deactivate a KeyBinding?WPF DataTrigger 可以停用 KeyBinding 吗?
【发布时间】:2015-02-28 00:40:48
【问题描述】:

我有一个带有一些 KeyBindings 的 ListView,可以让用户使用键盘快捷键移动和删除条目。但是,我不希望始终可以访问绑定。

用于添加、删除和移动条目的按钮控件的可见性与 ComboBox 的选择相关(只有某些用户可以编辑)。我还希望根据框选择停用键盘快捷键。

我还没有找到任何关于这是否可行的信息。大家觉得呢?

<ComboBox x:Name="TesterIdentityBox" ItemsSource="{Binding Path=TesterIdentityList, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Name" SelectedItem="{Binding Path=TesterIdentitySelection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  SelectedIndex="{Binding TesterIdentityIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

<ListView ItemsSource="{Binding TestViewList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedIndex="{Binding SelectedTestIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Path=SelectedTest}">
    <ListView.InputBindings>
        <KeyBinding Key="Up" Command="{Binding Path=MoveTestUpCommand}" CommandParameter="{Binding Path=SelectedTest.Description}" />
        <KeyBinding Key="Down" Command="{Binding Path=MoveTestDownCommand}" CommandParameter="{Binding Path=SelectedTest.Description}" />
        <KeyBinding Key="Delete" Command="{Binding Path=RemoveTestCommand}" />
    </ListView.InputBindings>

我使用带有 DataTriggers 的 Style Setter 来改变命令按钮的可见性,但我不知道什么(如果有的话)是 KeyBinding 等非可视元素的等价物。

【问题讨论】:

    标签: wpf data-binding key-bindings


    【解决方案1】:

    在这种情况下,最简单的方法是在您的MoveTestUpCommandMoveTestDownCommandRemoveTestCommand 中实现CanExecute() 方法。当您不希望用户能够执行这些操作时,此方法应返回 false。因此,您的KeyBindings 将不起作用,因为这些命令不会被执行。

    如果您的按钮的Command 属性也绑定到这些命令,这些按钮将根据CanExecute() 返回值自动更新其可用性(IsEnabled 属性)。要从视图模型更新视图状态,只需在相应命令上调用 RaiseCanExecuteChanged() 方法(但这取决于您的 ICommand 实现)。

    要根据按钮的可用性设置按钮的可见性,您可以使用以下内容:

    <Button 
      Command = "{Binding SampleCommand}" 
      Visibility = "{Binding IsEnabled, RelativeSource = {RelativeSource Self}, Converter = {StaticResource BooleanToVisibilityConverter}}"/>
    

    System.Windows.Controls 中有一个BooleanToVisibilityConverter 的实现。

    【讨论】:

    • 是的,我忘记了 CanExecute。我几乎从不使用它,但在这里效果很好。我决定不更改其他绑定,因为我已经有了一个可见性检查器,但下次我会记住这一点。非常感谢。
    • 经过一些测试,我注意到我的“删除”按钮被禁用,就像你提到的那样,但它一直被禁用,即使 CanExecute 为真。我认为这可能是因为 UI 没有更新,但我的实现似乎不包括 RaiseCanExecuteChanged 函数。对我来说,简单的解决方案是简单地删除 CanExecute 并将其更改为删除函数本身内部的检查。现在键和按钮都具有正确的行为。
    • 有人特别要求我回到 CanExecute 方法后,这个问题又困扰着我。在开始一个新问题后,我发现这是我的逻辑错误的组合:stackoverflow.com/questions/28910262/…
    猜你喜欢
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2011-08-17
    • 2013-12-27
    • 1970-01-01
    相关资源
    最近更新 更多