0

我的 WPF 应用程序有问题。

我有一个数据网格(Wpf Toolkit),我必须管理一个行验证......如果验证结果为假,我会认为另一行是不可选择的。

因此,我必须阻止对我编辑的当前行的选择。

我能怎么做?有任何想法吗?

4

1 回答 1

0

卢克,

你不是第一个问这个问题的人。它是当前 WPF 版本的一个主要缺点,其中没有用于 Selector 派生控件的 PreviewSelectionChangeEvent 等事件。这个问题唯一被社区接受的解决方案当然是 HACK 解决方案。这是方法。

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];

    }

}

希望这会引导您找到解决方案。

于 2009-10-31T00:44:25.137 回答