我有一个InvokeCommandAction
,它附加到一个TextBox
的GotFocus
事件上,代码如下:
<TextBox Grid.Row="0"
Grid.Column="1"
Width="40"
HorizontalAlignment="Right">
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding GotFocusCommand}" CommandParameter="Enter data [message to be displayed]" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
这样做很好,但我有几十个带有相同设置的TextBox
。我不想为每一个重复编写代码,而是希望将该触发器附加到所有类型为{x:Type TextBox}
的控件。
通常情况下,我会在Resources
部分设置属性,如下所示:
<UserControl.Resources>
<Style TargetType="TextBlock">
<Setter Property="Padding" Value="5,0,0,0" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</UserControl.Resources>
很遗憾,这种方法不适用于Triggers
:
附加属性"Triggers"只能应用于从"DependencyObject"派生的类型。
理想情况下,我想要做这样的事情:
<UserControl.Resources>
<Style TargetType="{x:Type TextBox}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding GotFocusCommand}" CommandParameter="{Binding Tag}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Style>
</UserControl.Resources>
我只需要设置每个文本框的
Tag
属性来指定要显示的消息。我这么做是正确的吗?我需要改用 ControlTemplate
或类似的东西吗?编辑:
我在这里看到了一个类似的问题:Interaction Triggers in Style in ResourceDictionary WPF 阅读该问题的答案后,我尝试了以下操作:
<UserControl.Resources>
<TextBox x:Key="TextBoxWithTag">
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding GotFocusCommand}" CommandParameter="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</UserControl.Resources>
那么就像这样将其分配给控件:
然后分配给一个控件,如下所示:
<ContentControl Grid.Row="0"
Grid.Column="1"
Width="40"
HorizontalAlignment="Right"
Content="{StaticResource TextBoxWithTag}"
Tag="test tag" />
这个也不起作用,仍然抱怨:
“Triggers”附加属性只能应用于派生自“DependencyObject”的类型。
编辑2:
这是“GotFocusCommand”的信息。它设置一个字符串的值,该字符串绑定到一个“TextBlock”。
这在我的ViewModel中:
private ICommand _gotFocusCommand;
public ICommand GotFocusCommand
{
get
{
if (_gotFocusCommand == null)
{
_gotFocusCommand = new DelegateCommand<string>(TextBoxGotFocus);
}
return _gotFocusCommand;
}
}
private void TextBoxGotFocus(string infoText)
{
CardInfoText = infoText;
}
然后是XAML代码:
<TextBlock Grid.Row="2"
Grid.Column="0"
Grid.ColumnSpan="2"
HorizontalAlignment="Center"
Text="{Binding CardInfoText}" />