Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to FocusManager.FocusedElement

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

like image 458
Twelve Avatar asked Oct 21 '11 13:10

Twelve


2 Answers

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.

like image 80
CodeNaked Avatar answered Sep 27 '22 15:09

CodeNaked


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.

like image 35
Rohit Vats Avatar answered Sep 27 '22 15:09

Rohit Vats