Telerik Product and Version
|
UI for WPF, no specific version. |
Supported Browsers and Platforms
|
Tested in desktop environment. |
Components/Widgets used (JS frameworks, etc.)
|
|
Bringing a programatically selected item into view on a RadGridView.
Your ViewModel may have added a new entity to the grid, or a function selected an item... that item is not in view. If you want that item visible it can be a bit complicated. This project is a simple behaviour which can be added to a RadGridView and scrolls the SelectedItem to the top line of the grid viewport.
The main obstacle is differentiating between a UI selection or programmatic selection.
Out of the box the RadGridView doesn't. Fortunately we can make an assumption that when the SelectionChanged event fires, if the Selected Item isn't in view, the user didn't click it!
A simple bit of maths with the GridViewScrollViewer can tell us if the Selected Item is in view or not and the rest is in the code below...
public
class
RadGridView_ScrollSelectedIntoViewBehaviour
{
public
static
readonly
DependencyProperty ScrollSelectedIntoViewProperty =
DependencyProperty.Register(
"ScrollSelectedIntoView"
,
typeof
(
bool
),
typeof
(RadGridView),
new
FrameworkPropertyMetadata(ScrollSelectedIntoViewPropertyChanged));
public
static
bool
GetScrollSelectedIntoView(DependencyObject obj)
{
return
(
bool
)obj.GetValue(ScrollSelectedIntoViewProperty);
}
public
static
void
SetScrollSelectedIntoView(DependencyObject obj,
bool
value)
{
obj.SetValue(ScrollSelectedIntoViewProperty, value);
}
private
static
void
ScrollSelectedIntoViewPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RadGridView grid = d
as
RadGridView;
if
(grid !=
null
)
{
grid.SelectionChanged += Grid_SelectionChanged;
}
}
private
static
void
Grid_SelectionChanged(
object
sender, SelectionChangeEventArgs e)
{
RadGridView grid = sender
as
RadGridView;
if
(grid ==
null
)
return
;
if
(!GetScrollSelectedIntoView(grid))
return
;
object
si = grid.SelectedItem;
if
(si !=
null
)
{
var scrollOffset = grid.Items.IndexOf(si) * grid.RowHeight;
var scrollViewer = grid.ChildrenOfType<GridViewScrollViewer>().First();
var svo = scrollViewer.VerticalOffset;
var svh = scrollViewer.ViewportHeight;
if
(scrollOffset < svo || scrollOffset > (svo + svh))
{
scrollViewer.ScrollToVerticalOffset(scrollOffset);
}
else
{
scrollViewer.ScrollToVerticalOffset(svo);
}
}
}
}
Adding it to a grid;
<
telerik:RadGridView
x:Name
=
"MyRadGridView"
ItemsSource
=
"{Binding EntityList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
SelectionMode
=
"Extended"
SelectionUnit
=
"FullRow"
GroupRenderMode
=
"Flat"
SelectedItem
=
"{Binding CurrentEntity, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
behaviours:RadGridView_ScrollSelectedIntoViewBehaviour.ScrollSelectedIntoView
=
"True"
>
</
telerik:RadGridView
>