简体   繁体   English

在DataGridComboBoxColumn中编辑单元格时如何获取“当前单元格”值?

[英]How to get the Current Cell value when you edit the cell in DataGridComboBoxColumn?

I am new to WPF, trying to fix up an autosuggest DataGridComboBoxColumn 我是WPF的新手,试图修复一个自动建议的DataGridComboBoxColumn

<DataGridComboBoxColumn x:Name="list_itemname" Width="*" Header="Item Name"  >
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="IsEditable" Value="True"/>
            <Setter Property="ItemsSource" Value="{Binding Path=itemlist}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

You have to catch event related to changing the cell: CellEditEnding. 您必须捕获与更改单元格有关的事件:CellEditEnding。 First you have to declare method that will handle the event: 首先,您必须声明将处理事件的方法:

void cellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    var editedComboBoxColumn = e.EditingElement as ComboBox;
}

and then hook up handler with your grid: 然后将处理程序与网格连接:

<DataGrid x:Name="grid" CellEditEnding="cellEditEnding" />

Instead of using a datagrid combobox column, I recommend you use a datagrid template column. 建议您不要使用datagrid组合框列,而应使用datagrid模板列。

Roughly 大致

    <DataGridTemplateColumn>
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox IsEditable="True" 
                          Text="{Binding PropertyInRow}" 
                          ItemsSource="{Binding itemlist}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>

Here PropertyInRow is the name of a propfull in a row viewmodel. 在这里,PropertyInRow是行视图模型中propprop的名称。 Whatever your itemssource of the datagrid is bound to being an observablecollection. 无论您的数据网格项源是什么,都注定是一个可观察的集合。

If you want to do something when the text changes then you can put code in the setter of that propfull. 如果您想在文本更改时执行某些操作,则可以将代码放入该属性的设置器中。

This is the mvvm pattern and you should learn that from the start if you plan on doing any serious wpf development. 这是mvvm模式,如果计划进行任何认真的wpf开发,则应该从一开始就学习这一点。 Certainly if you plan on working in a commercial wpf team because they all use mvvm. 当然,如果您打算在商业wpf团队中工作,因为他们都使用mvvm。

Also. 也。

If itemlist is not a property in the rowviewmodel and instead is somewhere in the window viewmodel then you'll want some relativesource on that binding. 如果itemlist不是rowviewmodel中的属性,而是位于窗口viewmodel中的某个位置,则需要在该绑定上有一些相对源。

If your ItemSource is a ListCollectView, you can get the current item like this: 如果您的ItemSource是ListCollectView,则可以这样获取当前项目:

public void OnCellValueChanged(object sender, CellValueChangedEventArgs e)
{
    var currentItem = itemlist.CurrentItem; // to get the whole current item

    // Or you just get the current changed cell value from the EventArgs:
    var currentValue = e.Value?.ToString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM