我正在尝试绑定文本框' PreviewTextInput'到viewmodel中的方法。 我关注this article 但我的方法从未被调用过。 这是我在XAML中的代码:
<UserControl x:Class="ConfigurationView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OPCUAProjectModule.Views"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="700">
.....
.....
.....
<TextBox x:Name="txtServer" Text="{Binding Server, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewTextInput" >
<i:InvokeCommandAction Command="{Binding IsAllowedInput}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
....
....
这里我们使用ViewModel代码:
public class ConfigurationViewModel : BindableBase, INotifyDataErrorInfo
{
....
....
public string Server
{
get
{
return this.server;
}
set
{
this.SetProperty(ref this.server, value);
}
}
private void IsAllowedInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
//Never enters here.
}
答案 0 :(得分:1)
如果您添加对Microsoft.Expressions.Interactions.dll
的引用(Project-&gt; Add Reference-&gt; Assemblies-&gt; Expenions in Visual Studio),您可以使用CallMethodAction
来调用方法:
<TextBox x:Name="txtServer" Text="{Binding Server, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewTextInput" >
<ei:CallMethodAction TargetObject="{Binding}" MethodName="IsAllowedInput" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
当然,该方法不能是private
:
public void IsAllowedInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
//...
}