2013-08-19 24 views
1

我正在嘗試創建一種樣式,這會讓所有DataGrid在失去焦點時選擇第-1行。我做:ToolKit DataGrid取消選擇LostFocus上的全部

<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的第二次程序崩潰。是否有可能沒有代碼?

+0

你只是試圖從'DataGrid'刪除選定的項目嗎? – Sheridan

+0

我試圖刪除選擇(不選擇任何內容)。 – Taras

+0

可能值得重新命名您的帖子來陳述您的*實際*目標。 – Sheridan

回答

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> 
0

一種更好的方式來實現去選擇所選的項目你實際的目標是相同類型的對象綁定那些在綁定到DataGrid.ItemsSource屬性爲DataGrid.SelectedItem屬性收集數據。當您要取消選擇的項目,你只要這個對象設置爲null

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

在視圖模型:

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

謝謝,很明顯,但我只是想要一種樣式來實現所有DataGrid中的行爲。我應該怎麼做LostFocus ..?轉到VM?使用System.Windows.Interactivity在事件上運行命令..?這太複雜了..恕我直言 – Taras

相關問題