豆瓣電台WP7用戶端 MVVM重構記錄之使用MVVM Light實現Event綁定

來源:互聯網
上載者:User

這次實現了MVVM Light事件的綁定。MVVM Light為事件綁定提供了很好的支援,它有很多種方式可以實現。對於支援Command的事件比如Button的Click事件那麼最簡單可以直接綁定Command。對於不支援Command的事件比如TextChanged可以使用InvokeCommandAction或者EventToCommand來綁定。這裡我就不展開了,因為自己也是一知半解,以免誤導看客。這次我示範使用EventToCommand來綁定HubTile的Tap事件。

在ViewModel裡定義一個RelayCommand:

namespaceDBFM7.ViewModel
{
    public classChannelTileViewModel: ViewModelBase
   {
        /// <summary>
        ///Initializes a new instance of the ChannelTileViewModel class.
       /// </summary>
       publicChannelTileViewModel()
        {
            TouchPanel.EnabledGestures = GestureType.Tap | GestureType.HorizontalDrag;

            this._TapCommand = newRelayCommand<string>(this.HubTile_Tap);
        }

        privateRelayCommand<string> _TapCommand;

        publicRelayCommand<string> TapCommand
        {
            get{ return_TapCommand; }
            set
           {
                _TapCommand = value;
                this.RaisePropertyChanged("TapCommand");
            }
        }

       private voidHubTile_Tap(string hubTile)
        {

         MessageBox.Show(hubTile);


        }

    }

}

 

在View添加xmlns:

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"    xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP71"

綁定tap:

     <toolkit:HubTile Grid.Row="0" Grid.Column="1"                              Margin="12,12,0,0"                             x:Name="OM" >                <i:Interaction.Triggers>                    <i:EventTrigger EventName="Tap">                        <cmd:EventToCommand Command="{Binding TapCommand}"                                             CommandParameter="{ Binding Title, ElementName=OM }" />                    </i:EventTrigger>                </i:Interaction.Triggers>            </toolkit:HubTile>

EventToCommand 的 Command綁定命令,CommandParameter綁定的是傳遞的參數。其中PassEventArgsToCommand可以傳遞事件的args。

我本來是要想傳遞事件的sender過去的,雖然可以實現,不過過於繁瑣,且在國外論壇看到這樣傳遞不符合MVVM的思想。

My stance on MVVM is:

View : knows about ViewModel

ViewModel : knows about Model (has NO knowledge of View)

Model : holds data. (has NO knowledge of ViewModel, View)

所以傳遞sender到VM是不合適的。

更多的關於事件綁定請參考:http://geekswithblogs.net/lbugnion/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx


下節我將在WP7中使用MVVM Light的Message機制實現頁面導航。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.