WPF数据网格组合框列:如何管理选择更改事件?

zujrkrfu  于 2023-02-10  发布在  其他
关注(0)|答案(4)|浏览(167)

我有一个数据网格,其中包含一个组合框列

<DataGridComboBoxColumn x:Name="DataGridComboBoxColumnBracketType" Width="70" Header="Tipo di staffa" SelectedValueBinding="{Binding type, UpdateSourceTrigger=PropertyChanged}">                    
            </DataGridComboBoxColumn>

我想要一个只有当用户更改组合框中的值时才触发的事件。我该如何解决这个问题?

rkue9o1l

rkue9o1l1#

我在CodePlex上找到了这个问题的解决方案。下面是它,做了一些修改:

<DataGridComboBoxColumn x:Name="Whatever">                    
     <DataGridComboBoxColumn.EditingElementStyle>
          <Style TargetType="{x:Type ComboBox}">
               <EventSetter Event="SelectionChanged" Handler="SomeSelectionChanged" />
          </Style>
     </DataGridComboBoxColumn.EditingElementStyle>           
</DataGridComboBoxColumn>

在代码隐藏中:

private void SomeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
     var comboBox = sender as ComboBox;
     var selectedItem = this.GridName.CurrentItem;

}
bmvo0sr5

bmvo0sr52#

CodePlex的@kevinpo提供的xaml代码和David Mohundro's blog的帮助,以编程方式:

var style = new Style(typeof(ComboBox));
style.Setters.Add(new EventSetter(ComboBox.SelectionChangedEvent, new SelectionChangedEventHandler(SomeSelectionChanged)));
dataGridComboBoxColumn.EditingElementStyle = style;
hwamh0ep

hwamh0ep3#

要完成Kevinpo的回答,您应该为后面的代码添加一些保护,因为selectionChanged事件使用datagridcolumncombobox触发了2次:
1)第一触发器:当您选择新项目时
2)第二次触发:选择新项目后单击其他数据网格列时
问题是,在第二个触发器上,ComboBox值为null,因为您没有更改选定的项。

private void SomeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var comboBox = sender as ComboBox;
    if (comboBox.SelectedItem != null)
    {
        YOUR CODE HERE
    }
}

那是我的问题,我希望它能帮助别人!

t8e9dugd

t8e9dugd4#

最近,让SelectionChanged事件在DataGridComboBoxColumn单元格上触发的问题一直困扰着我。我使用了以下解决方案:

private void DataGridView_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
    {
        if (e.Column.DisplayIndex == 3) //Use this IF statement to specifiy which combobox columns you want to attach the event to.
        {
            ComboBox? cb = e.EditingElement as ComboBox;
            if (cb != null)
            {
                // As this event fires everytime the user starts editing the cell you need to dettach any previously attached instances of "My_SelectionChanged", otherwise you'll have it firing multiple times.
                cb.SelectionChanged -= My_SelectionChanged;
                // now re-attach the event handler.
                cb.SelectionChanged += My_SelectionChanged;
            }
        }
    }

然后根据需要设置自定义SelectionChanged事件处理程序:

private void My_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // Your event code here...
    }

相关问题