2014-05-24 37 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,我發現後的問題,但不是解決方案:)你的解決方案工作完美,再次感謝。 –