2015-11-05 55 views
1

我已经成功地转换的事件的方法(用于视图模型使用)使用EventTriggerBehavior如下面的示例所示CallMethodAction(这里挑选用于说明一个页加载事件)。事件到视图模型方法VisualStateGroup

<i:Interaction.Behaviors> <core:EventTriggerBehavior EventName="Loaded"> <core:CallMethodAction TargetObject="{Binding Mode=OneWay}" MethodName="PageLoadedCommand"/> </core:EventTriggerBehavior> </i:Interaction.Behaviors>

然而,没有成功,当涉及到CurrentStateChanged事件的VisualStateGroup如下所示(是的,嵌套在<VisualStateGroup>块内作为CurrentStateChanged事件属于VisualStateGroup):

<i:Interaction.Behaviors> <core:EventTriggerBehavior EventName="CurrentStateChanged"> <core:CallMethodAction MethodName="CurrentVisualStateChanged" TargetObject="{Binding Mode=OneWay}"/> </core:EventTriggerBehavior> </i:Interaction.Behaviors>

我怀疑VisualStateGroup(或VisualStateManager)和事件可能存在问题。我这样说是因为我可以用这种方法来处理其他事件。我已经检查并重新检查了方法签名(事件参数传递格式),但没有机会。

如果您设法得到CurrentStateChanged事件触发如上(或使用替代方法),我非常想知道。

回答

1

但是没有成功,当谈到VisualStateGroup的CurrentStateChanged事件如下图所示

是的,EventTriggerBehavior不会为VisualStateGroup.CurrentStateChanged事件工作。

可行的方法是创建一个自定义行为,专门针对这种情况,请参阅this blog写道由马密涅瓦

这种行为可以帮助我们监视当前VisualStatus中的设置方法自定义属性(ViewModelState型),调用方法如你所愿:

public class MainViewModel : ViewModelBase 
{ 
     public enum ViewModelState 
     { 
      Default, 
      Details 
     } 

     private ViewModelState currentState; 
     public ViewModelState CurrentState 
     { 
      get { return currentState; } 
      set 
      { 
       this.Set(ref currentState, value); 
       OnCurrentStateChanged(value); 
      } 
     } 

     public RelayCommand GotoDetailsStateCommand { get; set; } 
     public RelayCommand GotoDefaultStateCommand { get; set; } 

     public MainViewModel() 
     { 
      GotoDetailsStateCommand = new RelayCommand(() => 
      { 
       CurrentState = ViewModelState.Details; 
      }); 

      GotoDefaultStateCommand = new RelayCommand(() => 
      { 
       CurrentState = ViewModelState.Default; 
      }); 
     } 

     public void OnCurrentStateChanged(ViewModelState e) 
     { 
      Debug.WriteLine("CurrentStateChanged: " + e.ToString()); 
     } 
} 

请检查我完成样品上Github

0

可能是由于最新的SDK,我设法使它与动态绑定(对于事件到方法模式)如下工作。

在XAML绑定到CurrentStateChanged事件为:

<VisualStateGroup CurrentStateChanged="{x:Bind ViewModel.CurrentVisualStateChanged}"> 

在视图模型提供CurrentStateChanged事件签名CurrentStateChanged()方法:

public void CurrentVisualStateChanged(object sender, VisualStateChangedEventArgs e) 
{ 
    var stateName = e?.NewState.Name; // get VisualState name from View 
    ... 
    // more code to make use of the VisualState 
} 

上面并没有为我工作一段时间回到现在,我试过VS2015更新2我怀疑是最新的SDK得到了增强?无论如何,现在您可以通过动态绑定在视图模型中获取VisualState名称,这是个好消息。

相关问题