7

I have application with several datagrids and export to excel command, which gets focused datagrid as a command parameter. Is it possible to bind CommandParameter to FocusManager.FocusedElement, or do I have to set them explicity?

Thanks in advance

Twelve
  • 578
  • 7
  • 15

2 Answers2

7

Yes, you can bind to the FocusedElement. Something like:

<Button ...
    CommandParameter="{Binding (FocusManager.FocusedElement), RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

Depending on your focus scopes, you may need to change the Window to another element.

But personally, I'd setup up the command's handler to see if the parameter is null. If it is then I'd programmatically get the FocusManager.FocusedElement.

var element = parameter as DataGrid;
if (element == null)
    element = FocusManager.FocusedElement as DataGrid.

You can also search up the visual tree as needed to the get the associated DataGrid.

CodeNaked
  • 40,753
  • 6
  • 122
  • 148
  • +1 for the xaml approach. But for code part, if i am following MVVM pattern and my command resides in my ViewModel, i shouldn't access my UI objects from there. Right? – Rohit Vats Oct 21 '11 at 14:20
  • 1
    @RV1987- If you pass it via the CommandParameter you are still accessing the UI object :) – CodeNaked Oct 21 '11 at 14:45
  • Xaml approach doesn't work for me, but it may be issue with Fluent Ribbon that I use. Code behind approach works, but you have to use function GetFocusedElement and pass it reference to main window – Twelve Oct 23 '11 at 10:35
1

Why can't you have the CLR property on your ViewModel say "SelectedDataGrid" which you updates whenever any of your DataGrid gets Focus. Simply used that property in your code, instead of passing it from your View.

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • I use prism and have several modules, so I'd have to add this property to every viewmodel, which of course isn't the best idea – Twelve Oct 21 '11 at 13:41