WPF datagrid双击一整行而不是选中单元格
WPF开发一个工具
需要双击datagrid的某一行显示详细数据并编辑,之前双击行(DatagridRow)每次都跳转到单元格上(DatagridCell)
经验证,需要修改datagrid样式的某几个属性值
datagrid的默认样式,写在App.xaml的资源样式里就行。重点在于最后两个属性的设置,selectionUnit——表示传递整行信息
MVVM模式用obserablecollection绑定到datagrid上,用fullrow即可传递整个某个子项的完整信息
<Style TargetType="{x:Type DataGrid}" >
<Setter Property="Background" Value="White"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="AlternationCount" Value="0"/>
<Setter Property="RowHeaderWidth" Value="0"/>
<Setter Property="SelectionUnit" Value="FullRow"/>
<Setter Property="SelectionMode" Value="Extended"/>
</Style>
datagrid的xaml代码 编辑或者双击某行显示相应的数据,绿色代码是mvvm模式双击命令绑定到后台MVVM的EditCmd上,传递参数就是选中项的某个属性值。SelectedItem.Index——index是我obserablecollection泛型类里的一个属性,可以替换(不是真正的index)
<Datagrid>
<DataGrid.InputBindings>
<MouseBinding
MouseAction="LeftDoubleClick"
Command="{Binding EditCmd}" CommandParameter="{Binding SelectedItem.Index,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"/>
</DataGrid.InputBindings>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<TextBlock Text="操作"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="{x:Type data:SprayRulerData}" >
<StackPanel Orientation="Horizontal">
<!--<TextBlock Margin="2,0,0,0" Text="" Foreground="#6472B1" />
<TextBlock Text="{Binding Id}" Foreground="#6472B1" Width="20" VerticalAlignment="Center"/>-->
<Button Content="编辑" Background="#F1F19E" Foreground="Black" Command="{Binding DataContext.EditCmd,ElementName=view}" CommandParameter="{Binding Index}" Margin="15,0,0,0" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</Datagrid>
MVVM下的EditCmd代码,双击或编辑按键都能跳转对应的数据窗口
EditCmd = new DelegateCommand<object>(Edit);
///
/// 编辑、更新数据
///
public void Edit(object o)
{
flag = false;
var s = (RMC.SprayRulerIndex)o;
if (o is RMC.SprayRulerIndex)
{
if (RulerModels != null)
{
foreach (var item in RulerModels)
{
if (item.Index == s)
{
rulerSelected = item;
}
}
}
if (rulerSelected != null)
{
System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
{
AddSprayView win = new AddSprayView();
((AddSprayViewModel)win.DataContext).EditCkickHandle(this, rulerSelected);
win.Show();
// win.Show();
}));
}
}
}