4

我正在尝试创建一种样式,使我的所有 DataGrid 在失去焦点时都选择行-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>

它仅在第一次失去焦点时起作用,但在第二次由于类型转换异常而导致程序崩溃。没有代码后面有可能吗?

4

2 回答 2

4

根据我的研究,依恋行为是我唯一可以接受的解决方案。希望这会对某人有更多帮助:

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>
于 2013-08-19T16:34:27.340 回答
1

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

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

在视图模型中:

Item = null; // de-selects the selected item
于 2013-08-19T13:07:32.640 回答