DataGrid中如何通过Trigger等方式实现右键选中Cell

saybookcat 2017-12-07 03:12:37
实现了一个DataGrid,选中时获得行和选中的单元格,通过右键菜单可以复制单元格的值,不过右键选中时 Cell不能被选中。
通过什么方式可以在xaml中实现右键选择cell时,先选中cell呢?


<Window.Resources>
<local:DataGridTextCellValueConverter x:Key="converter"/>

</Window.Resources>

<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>

<DataGrid ItemsSource="{Binding Persons}"
SelectedItem="{Binding CurrentRow}"
CurrentCell="{Binding CurrentText, Mode=OneWayToSource, Converter={StaticResource converter}}"
IsReadOnly="True"
SelectionMode="Single">
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy" Command="{Binding CopyCommand}" CommandParameter="{Binding CurrentText}"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>


DataGridTextCellValueConverter

public class DataGridTextCellValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var cellInfo = (DataGridCellInfo)value;
if (cellInfo==null || cellInfo.Column == null || cellInfo.Item == null) return string.Empty;
var cellControl = cellInfo.Column.GetCellContent(cellInfo.Item);
var textBlock = cellControl as TextBlock;
if (textBlock == null) return string.Empty;
return textBlock.Text;
}
}


引用了MvvmLight
MainViewModel

public class MainViewModel
{
public MainViewModel()
{
Persons = new ObservableCollection<PersonViewModel>();
Persons.Add(new PersonViewModel { Name = "ssss", Age = 12 });
Persons.Add(new PersonViewModel { Name = "xxxx", Age = 30 });
}

public ObservableCollection<PersonViewModel> Persons { get; set; }


private PersonViewModel currentRow;
public PersonViewModel CurrentRow
{
get
{
return currentRow;
}
set
{
currentRow = value;

if (currentRow != null)
{
Console.WriteLine("CurrentRow: Name = {0}, Age = {1} ",
currentRow.Name, currentRow.Age);
}
}
}

private string currentText;
public string CurrentText
{
get
{
return currentText;
}
set
{
currentText = value;
Console.WriteLine("CurrentText: " + currentText);
}
}

private ICommand _copyCommand;
public ICommand CopyCommand
{
get
{
if (_copyCommand == null)
{
_copyCommand = new RelayCommand<string>(OnCopyAction);
}
return _copyCommand;
}
}

private void OnCopyAction(string param)
{
if (string.IsNullOrWhiteSpace(param)) return;
Clipboard.Clear();
Clipboard.SetDataObject(param);
}
}
...全文
509 3 点赞 打赏 收藏 举报
写回复
3 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
saybookcat 2017-12-07
补上

        private static DependencyObject VisualUpwardSearch<M>(DependencyObject source)
        {
            while (source != null && source.GetType() != typeof(M))
            {
                if (source is Visual || source is Visual3D)
                    source = VisualTreeHelper.GetParent(source);
                else
                    source = LogicalTreeHelper.GetParent(source);
            }
            return source;
        }
  • 打赏
  • 举报
回复
saybookcat 2017-12-07
SelectedItem 已经可以标记选中的是哪一行,这里主要的问题是 DataGrid SelectionUnit的问题 ,当前默认是CellOrRowHeader ,由于需要获得行 又获得列,只能设置这一种了。而在鼠标点击行的时候 Cell先被记录 ,然后 Row被记录 ,这时候由于 已经切换到Row选中模式,Cell选中将不被触发 。 我现在用了一种不太好的方式实现实现这部分功能。

            <i:Interaction.Triggers>
                <i:EventTrigger EventName="PreviewMouseRightButtonDown">
                    <command:EventToCommand Command="{Binding DataContext.SelectedCellItemCommand,
                        RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" PassEventArgsToCommand="True"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>

        private readonly ICommand _selectCellItemCommand = null;

        public ICommand SelectedCellItemCommand
        {
            get { return _selectCellItemCommand.Relay<RoutedEventArgs>(SelectedCellItemCmdAction); }
        }

        private void SelectedCellItemCmdAction(RoutedEventArgs e)
        {
            var dataGridCell = VisualUpwardSearch<DataGridCell>(e.OriginalSource as DependencyObject) as DataGridCell;

            if (dataGridCell == null) return;
            dataGridCell.Focus();
            e.Handled = true;
        }
  • 打赏
  • 举报
回复
exception92 2017-12-07
右键点击的时候 DataGrid已经失去焦点,除非在数据类中手动增加一个选中属性,选择行的时候更改它的值为True,再根据Trigger判定它的值改变背景色。
  • 打赏
  • 举报
回复
相关推荐
发帖
WPF/Silverlight
加入

8627

社区成员

WPF/Silverlight相关讨论
申请成为版主
帖子事件
创建了帖子
2017-12-07 03:12
社区公告
暂无公告