2017-04-12 79 views
0

我想了解如何在UWP项目中设置EventTriggerBehaviors。 所以我明白,我需要有Microsoft.Xaml.Behaviors.Uwp.Managed安装的软件包,并在我的XAML文件中声明下面的命名空间:UWP EventTriggerBehaviors按钮GotFocus

xmlns:Core="using:Microsoft.Xaml.Interactions.Core" 
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" 

本身的按钮应该被声明为:

<Button x:Name="btnTest > 
    <Interactivity:Interaction.Behaviors> 
     <Core:EventTriggerBehavior EventName="GotFocus" > 
      <Core:EventTriggerBehavior.Actions> 
       <Core:InvokeCommandAction Command="{Binding ... }" /> 
      </Core:EventTriggerBehavior.Actions> 
     </Core:EventTriggerBehavior> 
    </Interactivity:Interaction.Behaviors> 
</Button> 

但后来我迷路了......我想要的是一旦按钮获得焦点,它会在文本框中设置一些文本(基于按钮名称)。

我需要一个服务,什么应该是ViewModel代码?

实际上,是否有人能够推荐有关这个主题的优秀阅读,例子,书籍......?

更新以下詹姆斯回复: 的XAML InvokeCommandAction变为:

<Core:InvokeCommandAction Command="{Binding OnButtonFocusCommand}" CommandParameter="{Binding Name, ElementName=btnTest}" /> 

但我怎么得到的视图模型的方法中的参数?

回答

1

InvokeCommandAction Command属性需要在视图模型中实现一个ICommand,以便在触发EventTriggerBehavior时执行操作。

您可能必须在XAML是这样的:

<Button x:Name="btnTest"> 
     <Interactivity:Interaction.Behaviors> 
      <Core:EventTriggerBehavior EventName="GotFocus"> 
       <Core:EventTriggerBehavior.Actions> 
        <Core:InvokeCommandAction Command="{Binding OnButtonFocusCommand}" /> 
       </Core:EventTriggerBehavior.Actions> 
      </Core:EventTriggerBehavior> 
     </Interactivity:Interaction.Behaviors> 
    </Button> 

然后在绑定的视图模型,你就必须与此类似:

public ViewModel() 
    { 
     OnButtonFocusCommand = new DelegateCommand(() => 
     { 
      this.TextBoxText = "Hello, World"; 
     }); 
    } 

    public ICommand OnButtonFocusCommand { get; private set; } 

的DelegateCommand没有内置在但是你可以在网上找到很多DelegateCommand或RelayCommand的实现。

编辑:您还可以使用这样的传递的参数做到这一点:

public ViewModel() 
    { 
     OnButtonFocusCommand = new DelegateCommand<RoutedEventArgs>(args => 
      { 
       this.TextBoxText = "Hello, World"; 
      }); 
    } 

的RoutedEventArgs将是你通过参数的类型。在Focus事件传递的情况下,这是您将收到的参数。对于这些场景,您需要DelegateCommand{T}

我引用的DelegateCommand的示例还有一个机制,通过验证模型来检查是否运行该操作。你能做到这一点,像这样:

public ViewModel() 
    { 
     OnButtonFocusCommand = new DelegateCommand<RoutedEventArgs>(args => 
      { 
       this.TextBoxText = "Hello, World"; 
      }, 
      args => args.OriginalSource is TextBox); 
    } 

您的方案与更新文本框的文本,你需要创建在您的视图模型的属性(在我的例子中,我展示了TextBoxText更新)。然后,该属性需要绑定到XAML中TextBox的Text属性。

对于需要关注的事物,我会建议您查看一下MVVM框架(可能是MvvmLight),如果您尚未阅读,请阅读它。

此外official Microsoft samples on GitHub也可能涵盖了很多可能对您有用的主题。

如果您需要更多信息,请联系我,我很乐意提供帮助。

+0

谢谢詹姆斯,你的回复非常有用,但是不完整。如果我从命令参数传递一个值,我该如何接收它? –

+0

@FranckE我已经更新了我的答案,显示了通过参数传递给命令的DelegateCommand {T}场景。 –

+1

谢谢,这个作品很棒:) –