C# UWP EventTriggerBehaviors到按钮焦点
我试图了解如何在UWP项目中设置EventTriggerBehavior。 因此,我知道我需要安装包Microsoft.Xaml.Behaviors.Uwp.Managed,并在我的Xaml文件中声明以下名称空间:C# UWP EventTriggerBehaviors到按钮焦点,c#,xaml,uwp,behavior,eventtrigger,C#,Xaml,Uwp,Behavior,Eventtrigger,我试图了解如何在UWP项目中设置EventTriggerBehavior。 因此,我知道我需要安装包Microsoft.Xaml.Behaviors.Uwp.Managed,并在我的Xaml文件中声明以下名称空间: xmlns:Core="using:Microsoft.Xaml.Interactions.Core" xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" 按钮本身应声明为: <Button x:Name="btn
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>
InvokeCommandAction命令属性需要在视图模型中实现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>
尽管DelegateCommand不是内置于平台中的,但您可以在线找到许多或RelayCommand的实现
编辑:您也可以使用传递的参数执行此操作,如下所示:
public ViewModel()
{
OnButtonFocusCommand = new DelegateCommand<RoutedEventArgs>(args =>
{
this.TextBoxText = "Hello, World";
});
}
公共视图模型()
{
OnButtonFocusCommand=新的DelegateCommand(args=>
{
this.TextBoxText=“你好,世界”;
});
}
RoutedEventArgs将是您要传递的参数类型。对于焦点事件传递的内容,这是您将收到的参数。对于这些场景,您将需要
我提到的DelegateCommand示例也有一种机制,通过验证模型来检查是否运行操作。您可以这样做:
public ViewModel()
{
OnButtonFocusCommand = new DelegateCommand<RoutedEventArgs>(args =>
{
this.TextBoxText = "Hello, World";
},
args => args.OriginalSource is TextBox);
}
公共视图模型()
{
OnButtonFocusCommand=新的DelegateCommand(args=>
{
this.TextBoxText=“你好,世界”;
},
args=>args.OriginalSource是文本框);
}
对于更新文本框文本的场景,需要在视图模型中创建一个属性(在我的示例中,我显示了正在更新的文本框文本)。然后,该属性需要绑定到XAML中TextBox的Text属性
对于需要了解的内容,我建议您先了解一下MVVM框架(可能是MvvmLight),如果您还没有这样做的话,请仔细阅读
此外,本手册可能涵盖许多对您可能有用的主题
如果您需要更多信息,请与我联系,我很乐意为您提供帮助。谢谢您,詹姆斯,您的回复非常有用,但不完整。如果我从commandparameter传递一个值,我如何接收它?@FranckE我已经更新了我的答案,显示了DelegateCommand{T}场景,在该场景中,您将通过一个参数传递给命令。
public ViewModel()
{
OnButtonFocusCommand = new DelegateCommand<RoutedEventArgs>(args =>
{
this.TextBoxText = "Hello, World";
});
}
public ViewModel()
{
OnButtonFocusCommand = new DelegateCommand<RoutedEventArgs>(args =>
{
this.TextBoxText = "Hello, World";
},
args => args.OriginalSource is TextBox);
}