2017-07-04 47 views
0

我的代码如下。我不知道命令是否正确执行ToolbarItem。编译没有错误。当点击了baritem时,什么也没有发生。ToolBar中的Toolbaritem不点击

--- Xaml 

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
      xmlns:local ="clr-namespace:SembIWIS.View" 
      BackgroundColor="White" 
      Title="Repair and Service"   
      x:Class="MyMainMenu"> 
    <ContentPage.ToolbarItems> 
     <ToolbarItem Name="MenuItem1" Order="Primary" Icon="itemIcon1" Command="{Binding Item1Command}" Priority="0" /> 
     <ToolbarItem Name="MenuItem2" Order="Primary" Icon="itemIcon2" Priority="1" /> 
    </ContentPage.ToolbarItems> 

    <local:Product> 
    </local:Product> 

    <local:Service> 
    </local:Service> 

</TabbedPage> 


--------- Code Behind: 

public partial class MyMainMenu : TabbedPage 
    { 
     public ICommand Item1Command { get; private set; } 

     public MyMainMenu() 
     { 
      InitializeComponent(); 

      BindingContext = this; 

      NavigationPage.SetHasBackButton(this, true); 
      Init(); 
     } 

     private void Init() 
     { 

      this.Item1Command = new Command((sender) => 
      { 
       Navigation.PushAsync(new UpdateProduct()); 
      }); 


} 
+0

你还没有为你的视图设置绑定上下文,所以'Command =“{Binding Item1Command}”'没有绑定任何东西。一个短期的解决方法是在'MyMainMenu'构造函数中设置绑定上下文:'BindingContext = this;',尽管您可能想要调查MVVM模式并将您的ViewModel移动到一个对UI不了解的单独的类。 – Damian

+0

这是在同一页面上完成的。你能否向我展示如何以及在何处添加绑定上下文。 – MilkBottle

+0

我更新了我的评论以解释(我过早地输入)。 – Damian

回答

0

从评论我收集你忘了添加BindingContext。虽然您现在确实添加了它,但时机不对。在设置BindingContext之前,您需要执行Init();方法。

当设置了BindingContext时,此时一切都会接通,除非您正确实施INotifyPropertyChanged接口,否则您所做的任何更改都不会被提取。总之,对于这个问题,适应您的代码如下:

public MyMainMenu() 
{ 
    InitializeComponent(); 

    NavigationPage.SetHasBackButton(this, true); 
    Init(); 

    BindingContext = this; 
} 

在评论关于你的问题,关于性能和单元测试:

没有性能上的差异,因为两者MVVM框架您将使用意愿执行这个非常相同的代码,只会自动为你做。如果有的话,MVVM框架可能会慢一点,因为它可能会通过反射或类似的方式解析您的ViewModels。如果你想做单元测试,你将不得不将你的代码分解成一个单独的ViewModel,并将其设置为你的BindingContext。例如看看这个blog post关于使用FreshMvvm与单独的Views和ViewModels。

+0

只是一个想法。比较这种方法和Mvvm Binding for命令,这对于单元测试更容易?是否有任何性能差异? – MilkBottle

+0

我已经用这个答案更新了问题 –