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>

フォーカスが失われたのは初めてですが、2回目は型変換例外のためにプログラムがクラッシュします。コードビハインドなしで可能ですか?

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 に答える