2011-12-28 54 views
0

我想將一個按鈕與datagrid綁定到一個自定義命令。在數據網格中綁定一個命令

但由於某種原因,該命令不會被執行。

這是XAML:

<Grid Name="LayoutRoot"> 
     <ListView Name="ListView1" 
      ItemsSource="{Binding}" 
      IsSynchronizedWithCurrentItem="True"> 
      <ListView.ItemContainerStyle> 
       <Style TargetType="ListViewItem"> 
        <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 
       </Style> 
      </ListView.ItemContainerStyle> 
      <ListView.View> 
       <GridView> 
        <GridViewColumn Header="ID" Width="100"> 
         <GridViewColumn.CellTemplate> 
          <DataTemplate> 
           <TextBox Text="{Binding Path=id,Mode=OneWay}" 
           Margin="-6,0,-6,0" /> 
          </DataTemplate> 
         </GridViewColumn.CellTemplate> 
        </GridViewColumn> 
        <GridViewColumn Header="Name" Width="100"> 
         <GridViewColumn.CellTemplate> 
          <DataTemplate> 
           <TextBox Text="{Binding Path=name,Mode=OneWay}" 
           Margin="-6,0,-6,0" /> 
          </DataTemplate> 
         </GridViewColumn.CellTemplate> 
        </GridViewColumn> 
        <GridViewColumn Header="Path" Width="50"> 
         <GridViewColumn.CellTemplate> 
          <DataTemplate> 
           <TextBox Text="{Binding Path=path,Mode=OneWay}" 
           Margin="-6,0,-6,0" /> 
          </DataTemplate> 
         </GridViewColumn.CellTemplate> 
        </GridViewColumn> 
        <GridViewColumn Header="Update" Width="50"> 
         <GridViewColumn.CellTemplate> 
          <DataTemplate> 
           <Button CommandParameter="{Binding id}" Command="{Binding ???????????}" Content="Edit"/> 
          </DataTemplate> 
         </GridViewColumn.CellTemplate> 
        </GridViewColumn> 
       </GridView> 
      </ListView.View> 
     </ListView> 
    </Grid> 
</Window> 

我應該寫的,而不是什麼??????????以顯示帶有ID的消息。


找到了解決此:

WPF DataGrid - Button in a column, getting the row from which it came on the Click event handler

+1

您的viewmodel的外觀如何? – DHN 2011-12-28 21:43:36

回答

1

我認爲問題是細胞DataContext。在DataTemplate之內,它看不到父上下文。嘗試將您的命令添加到Resources並執行類似操作:

<DataTemplate> 
    <Button CommandParameter="{Binding id}" Command="{StaticResource yourCommand}" Content="Edit"/> 
</DataTemplate> 
+0

讓我知道如果將資源添加命令會有一些問題。 – 2011-12-29 09:57:14

0

創建從ICommand接口的命令繼承。

public class ShowMessageWithIdCommand : ICommand 
{ 
// Implement it members 
} 

在您的視圖模型:

public ICommand ShowMessageWithIdCommand 
{ 
    get{return new ShowMessageWithIdCommand(...);} 
} 

然後你?????將是:ShowMessageWithIdCommand

更多細節,你可以在這裏找到:http://msdn.microsoft.com/en-us/magazine/dd419663.aspx