在Josh Smith 的文章“ 具有Model-View-ViewModel設(shè)計模式的WPF應(yīng)用程序”中,作者說:(1)在設(shè)計良好的MVVM架構(gòu)中,大多數(shù)視圖的背后代碼應(yīng)為空,或者最多只能包含操縱該視圖中包含的控件和資源的代碼。(2)有時也有必要在與ViewModel對象進(jìn)行交互的View的代碼隱藏中編寫代碼,例如,鉤住事件或調(diào)用否則很難從ViewModel本身調(diào)用的方法。我的問題是,如下所示,為什么這樣的方法AttachedCommandBehavior或InvokeCommandAction試圖避免編碼背后的編碼。讓我解釋更多細(xì)節(jié)。就(1)而言,我認(rèn)為與AttachedCommandBehavior中的以下情況類似。為界沒有實現(xiàn)ICommandSource的MouseRightButtonDown,你不能經(jīng)常綁定的事件和ICommand,但可以用做AttachedCommandBehavior。<!-- I modified some code from the AttachedCommandBehavior to show more simply --><Border> <local:CommandBehaviorCollection.Behaviors> <local:BehaviorBinding Event="MouseRightButtonDown" Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/> </local:CommandBehaviorCollection.Behaviors></Border>要么我們可以使用System.Windows.Interactivity.InvokeCommandAction。<Border xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" > <i:Interaction.Triggers> <i:EventTrigger EventName="MouseRightButtonDown"> <i:InvokeCommandAction Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/> </i:EventTrigger> </i:Interaction.Triggers></Border>但,我們使用下面的XAML及其代碼背后的Border_MouseRightButtonDown方法,該方法鏈接到上述(2)Josh Simth。<Border MouseRightButtonDown ="Border_MouseRightButtonDown"/>我認(rèn)為使用上面的codebehind并不錯,因為兩者之間的區(qū)別僅在于綁定命令或添加事件處理程序的地方。你怎么看待這件事?
為什么要避免WPF MVVM模式中的代碼隱藏?
月關(guān)寶盒
2019-11-13 09:24:45