我创建了一个简单的XAML页面:
<Page.DataContext>
<local:MainPageViewModel />
</Page.DataContext>
<Interactivity:Interaction.Behaviors>
<Core:DataTriggerBehavior Binding="{Binding MyNumber}" Value="3">
<Core:CallMethodAction MethodName="TestMethod" TargetObject="{Binding ElementName=page}" />
<Core:CallMethodAction MethodName="ViewModelMethod" TargetObject="{Binding Mode=OneWay}" />
</Core:DataTriggerBehavior>
</Interactivity:Interaction.Behaviors>
<Grid>
<TextBox
Margin="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding MyNumber,
Mode=TwoWay}"
TextWrapping="Wrap" />
</Grid>
此页面的ViewModel:
public class MainPageViewModel : INotifyPropertyChanged
{
private int _myNumber;
public int MyNumber
{
get { return _myNumber; }
set
{
_myNumber = value;
RaisePropertyChanged("MyNumber");
Debug.WriteLine("Property MyNumber changed.");
}
}
public void ViewModelMethod()
{
Debug.WriteLine("ViewModelMethod called.");
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion INotifyPropertyChanged
}
在后面的页面代码中,我添加了以下方法:
public void TestMethod()
{
Debug.WriteLine("Method TestMethod called.");
}
当我在TextBox中输入数字3时,只会执行第二个CallMethodAction。
后面的代码中的TextMethod不会执行。为什么?我在Windows Phone 8中从未遇到过这个问题。
答案 0 :(得分:0)
找到解决方案!在Windows Phone 8.0中,您必须将TargetObject属性设置为在后面的代码中调用方法。在Windows Phone 8.1中,根本不设置TargetObject。有效的代码是:
<Core:CallMethodAction MethodName="TestMethod" />
尽管如此,如果方法不存在,我仍然认为至少应该抛出一个错误...
答案 1 :(得分:0)
这适用于我,Windows Phone 8.1 ...
XAML页面
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Tapped">
<Core:CallMethodAction MethodName="TestMethod" TargetObject="{Binding ElementName=page}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
基于Tappe事件,但我认为in将适用于您的情况。
对于方法,重要!把它公开。
public void TestMethod(object sender, TappedRoutedEventArgs e)
{
Debug.WriteLine("TestMethod");
}