2014-05-24 38 views
0

嗨,我尝试添加AppBarButton在ListView结合MVVM接力指挥和视图模型绑定命令RelayCommand这里是我的XAML代码AppBarButton不ListView中

<DataTemplate x:Key="MyTemplage" > 
     <Grid HorizontalAlignment="Stretch"> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="auto"></RowDefinition> 
      </Grid.RowDefinitions> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="4*" /> 
       <ColumnDefinition Width="1*" /> 
       <ColumnDefinition Width="1*" /> 
      </Grid.ColumnDefinitions> 
    <AppBarButton Grid.Column="1" Command="{Binding DoCommand,Mode=OneWay}"> 
       <AppBarButton.Icon> 
        <BitmapIcon UriSource="ms-appx:///assets/doIcon.png"></BitmapIcon> 
       </AppBarButton.Icon>      
      </AppBarButton> 
      </DataTemplate> 
<ListView HorizontalAlignment="Left" Margin="0,45,0,0" Background="Khaki" VerticalAlignment="Top" ItemsSource="{Binding AList, Mode=TwoWay}" 
     ItemTemplate="{StaticResource MyTemplage}"> 
    </ListView> 

这里是在VM我的继电器命令代码

private RelayCommand _DoCommand; 

    /// <summary> 
    /// Gets. 
    /// </summary> 
    public RelayCommand DoCommand 
    { 
     get 
     { 
      return _DoCommand 
       ?? (_DoCommand = new RelayCommand(
            () => 
             { 
              DoSomething(); 
             })); 
     } 
    } 

DoCommand在ViewModel中没有引发。如果我在后面的代码中注册单击事件处理程序,它工作正常如果我在Page.Bottombar中使用它,AppBarButton也可以使用MVVM。

有什么想法?

回答

2

的问题是,ListView控件的DataTemplate内的结合不是视图模型对象,但不同的DataContext,在你的情况下,它绑定到一个名为ALIST列表,它是视图模型内包含模型的列表类 - 所以绑定引擎基本上在该模型类中寻找DoCommand。

为了让绑定工作,您必须确保绑定指向实际位于RelayCommand的整个ViewModel DataContext。你能做到这一点的方法之一是绑定到你的页面元素的一些已在DataContext设置为全视图模型:

Command="{Binding DataContext.DoCommand, ElementName=pageRoot, Mode=OneWay}" 

在这种情况下,我结合pageRoot,其中pageRoot是的名称您的页面的根页面元素具有适当的DataContext集--ViewModel,其中的RelayCommand实际上是。

+0

感谢igrali,我发现后的问题,但不是解决方案:)你的解决方案工作完美,再次感谢。 –