2015-11-05 54 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名稱,這是個好消息。

相關問題