2013-01-08 48 views
0

我的程序中有一個要求,即一旦在組合框中選擇了一個項目,組合框中的對象(從ViewModel)就會被更新。目前,只有通過按Enter鍵或離開單元格提交編輯,對象纔會更新。用戶不需要額外的步驟。.NET 4.0 DataGridCombobox SelectionChanged問題

我的想法是有選擇組合框中的項目的行爲觸發CommitEdit()方法,然後CancelEdit()。但是,我似乎無法找到掛鉤到DataGridComboBoxColumn的SelectionChanged事件的方式,因爲它不可用。

其他建議一直在viewmodel中偵聽屬性更改事件,但直到單元格編輯完成後才更改屬性。

任何人都可以想出一種方法來導致DataGridCombobox中的新項目(索引)的選擇來關閉單元格的編輯,就好像用戶按Enter鍵或離開單元格一樣嗎?

注意:由於客戶限制,我無法使用.NET 4.5。

回答

1

我有類似的問題,但我剛剛發現解決方案使用附加屬性,這可能不完全解決您的問題,但它會幫助在數據網格選擇更改問題。

下面是附加屬性和處理程序方法

public static readonly DependencyProperty ComboBoxSelectionChangedProperty = DependencyProperty.RegisterAttached("ComboBoxSelectionChangedCommand", 
                               typeof(ICommand), 
                               typeof(SpDataGrid), 
                               new PropertyMetadata(new PropertyChangedCallback(AttachOrRemoveDataGridEvent))); 


public static void AttachOrRemoveDataGridEvent(DependencyObject obj, DependencyPropertyChangedEventArgs args) 
{ 
    DataGrid dataGrid = obj as DataGrid; 
    if (dataGrid != null) 
    { 
     if (args.Property == ComboBoxSelectionChangedProperty) 
     { 
     dataGrid.SelectionChanged += OnComboBoxSelectionChanged; 
     } 
    } 
    else if (args.OldValue != null && args.NewValue == null) 
    { if (args.Property == ComboBoxSelectionChangedProperty) 
     { 
     dataGrid.SelectionChanged -= OnComboBoxSelectionChanged; 
     } 
} 
} 

private static void OnComboBoxSelectionChanged(object sender, SelectionChangedEventArgs args) 
{ 
    DependencyObject obj = sender as DependencyObject; 
    ICommand cmd = (ICommand)obj.GetValue(ComboBoxSelectionChangedProperty); 
    DataGrid grid = sender as DataGrid; 

    if (args.OriginalSource is ComboBox) 
    { 
    if (grid.CurrentCell.Item != DependencyProperty.UnsetValue) 
    { 
     //grid.CommitEdit(DataGridEditingUnit.Row, true); 
     ExecuteCommand(cmd, grid.CurrentCell.Item); 
    } 
    } 
} 

SpDataGrid是,我從數據網格繼承定製控制。

我在generic.xaml中添加了下面的樣式,因爲我使用了resourcedictionary風格(你當然可以在datagrid中添加)。

<Style TargetType="{x:Type Custom:SpDataGrid}"> 
    <Setter Property="Custom:SpDataGrid.ComboBoxSelectionChangedCommand" Value="{Binding ComboBoxSelectionChanged}"/> 
</Style> 

ComboBoxSelectionChanged是我的viewmodel中的命令。 OnComboBoxSelectionChanged我評論了commitedit,因爲在我的情況下,值已經更新。

讓我知道,如果有什麼不明確或任何問題。希望這可以幫助。