【发布时间】:2014-06-23 05:37:57
【问题描述】:
我有一个程序,其中包含一个 DataGrid 和一个填充有按钮的 DataGridTemplateColumn。由于行数是可变的,所有按钮的 Command 都绑定到相同的功能。但是,这意味着我现在需要发送一个 CommandParameter 来识别按钮的“索引”(等于它所在行的索引)。这是我想不通的。我应该发送什么作为 CommandParameter 来了解按钮的索引?
请参阅下面的 .xaml(删除了与当前问题无关的所有内容)。 Button CommandParameter 是我要填写的内容。
<UserControl x:Class="WPF.NOptionsTab"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d"
xmlns:l="clr-namespace:WPF">
<Grid>
<Grid.Resources>
<DataTemplate x:Key="CablesColumn">
<Button Command="{Binding Path=DataContext.CablesClick, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}"
CommandParameter="{Binding }"
Width="50"
ToolTip="Set cables pulled in this phase."
Content="Set"/>
</DataTemplate>
</Grid.Resources>
<DataGrid x:Name="PhaseGrid"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Cables" CellTemplate="{StaticResource CablesColumn}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
【问题讨论】:
-
您是否可以使用选定的网格行,或者假设您必须在按下按钮之前选择行/将按钮带出网格并且仅在选择某些内容时启用。然后您可以将选定的行绑定到您的视图模型并在方法中使用它?
-
你不需要索引或类似的东西。您当前的代码很好。使用
CommandParameter="{Binding}"会将相关数据项(数据行)发送到命令。该命令应使用数据项而不是索引或其他不相关信息进行操作。 -
哇,HighCore。就是这样。我承认我什至没有按原样尝试过代码,因为我从来没有想过这甚至是合法的代码。但是当然。只需将其复制到答案中,我会标记它。哇。