ToolKit DataGrid取消选择LostFocus上的所有内容

时间:2013-08-19 11:56:48

标签: wpf datagrid toolkit

我试图创建一种样式,当我们失去焦点时,它会让我的所有DataGrids选择第-1行。我正在做:

<Style TargetType="{x:Type DataGrid}">
    <Style.Triggers>
        <EventTrigger RoutedEvent="DataGrid.LostFocus">
            <BeginStoryboard>
                <Storyboard>
                    <Int32AnimationUsingKeyFrames Storyboard.TargetProperty="(DataGrid.SelectedIndex)">
                        <DiscreteInt32KeyFrame KeyTime="00:00:00" Value="-1" />
                    </Int32AnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Style.Triggers>
</Style>

它仅在第一次失去焦点时起作用,但是在第二次程序因类型转换ecxeption而崩溃时。没有代码可以吗?

2 个答案:

答案 0 :(得分:2)

根据我的研究,附加行为是我唯一可以接受的解决方案。希望这会有助于更多人:

public class DataGridBehavior
{
    public static readonly DependencyProperty IsDeselectOnLostFocusProperty =
    DependencyProperty.RegisterAttached("IsDeselectOnLostFocus", typeof(bool), typeof(DataGridBehavior), new UIPropertyMetadata(false, PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        var dg = dependencyObject as DataGrid;
        if (dg == null)
            return;

        if (e.NewValue is bool == false)
            return;

        if ((bool)e.NewValue)
            dg.LostFocus += dg_LostFocus;
    }

    static void dg_LostFocus(object sender, RoutedEventArgs e)
    {
        (sender as DataGrid).SelectedIndex = -1;
    }

    public static bool GetIsDeselectOnLostFocus(DataGrid dg)
    {
        return(bool)dg.GetValue(IsDeselectOnLostFocusProperty);
    }

    public static void SetIsDeselectOnLostFocus(DataGrid dg, bool value)
    {
        dg.SetValue(IsDeselectOnLostFocusProperty, value);
    }
}

然后:

<Style TargetType="{x:Type DataGrid}">
    <Setter Property="helpers:DataGridBehavior.IsDeselectOnLostFocus" Value="True"/>
</Style>

答案 1 :(得分:0)

实现取消选择所选项目的实际目标的更好方法是绑定与绑定到DataGrid.ItemsSource属性的集合数据中的对象类型相同的对象DataGrid.SelectedItem属性。如果要取消选择所选项目,只需将此对象设置为null

<DataGrid ItemsSource="{Binding Items}" SelectedItem="{Binding Item}" />

在视图模型中:

Item = null; // de-selects the selected item