views:

110

answers:

1

I have a problem with my WPF application.

I have a datagrid (Wpf Toolkit), I have to manage a Row validation...if validation result is false I would that the other row isn't selectable.

Therefore I have to block the selection to current row that I edit.

How can I do? Any ideas?

A: 

Luke,

You are not the first to ask this question. Its a major drawback to current WPF version where there is no event such as PreviewSelectionChangeEvent for Selector derived control. The only community accepted solution to this problem is of course a HACK solution. Here is the approach.

public void OnSelectionChange(object sender, SelectionChangedEventArgs e)
{
    // Selector is based class for all selection enabled control
    // (not too sure if your datagrid
    // derives from the same class, you will need to check).
    var selector = e.OriginalSource as Selector;
    if (selector == null) return;

    // Get the old items and new items from the selection change
    // (note, that they are IList type).
    // Let's assume that your datagrid will only allow single cell selection only,
    // ie. newItems.Count == 1
    var newItems = e.AddedItems;
    var oldItems = e.RemovedItems;

    // May need to check if not null first.
    if (oldItems.Count == 1 && newItems.Count == 1)
    {
        // Checking logic for the first (and only) items.
        // Casting the item into our known type.
        var myObject = newItems[0] as myType;

        // Notice that I reversed the logic, this is because we are
        // only interested in when our logic fails and we need to revert
        // the selection to the old item,
        // otherwise the new item is selected by default
        if (!(myObject != null && SomeOtherCondition))
            selector.SelectedItem = oldItems[0];

    }

}

Hope that leads you to a solution.

Tri Q