WPF DataGridComboBoxColumn绑定

时间:2018-09-02 08:50:44

标签: wpf datagridcomboboxcolumn

尝试使用DataGridComboBoxColumn更新我的实体框架时出现麻烦

我有一个绑定到自定义模型(FunctionPrinterLookupModel)的数据网格,该模型基本上是在建筑物周围的打印机和函数之间进行的查找。这些功能都是静态的,但是我希望用户能够选择使用该功能的打印机。

<DataGrid Grid.Row="1" x:Name="gridLookup" AutoGenerateColumns="False" Width="500" RowEditEnding="gridLookup_RowEditEnding" Margin="20">
                    <DataGrid.DataContext>
                        <Models:Printer/>
                    </DataGrid.DataContext>
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Function" Width="*" IsReadOnly="True" Binding="{Binding FunctionName}"/>
                        <!--<DataGridTextColumn Header="Printer" Width="*" Binding="{Binding PrinterName, UpdateSourceTrigger=PropertyChanged}"/>-->
                        <DataGridComboBoxColumn x:Name="ddlPrinters" Header="Printer" Width="*"  SelectedValueBinding="{Binding PrinterID, Mode=TwoWay}" SelectedValuePath="{Binding PrinterID, Mode=TwoWay}" DisplayMemberPath="{Binding PrinterName}"/>
                    </DataGrid.Columns>
                </DataGrid>

 private void gridPrinters_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        if (e.EditAction == DataGridEditAction.Commit)
        {
            Printer printer = (Printer)e.Row.Item;
            if (printer.PrinterID != 0)
            {
                Printer printerDB = context.Printers.Where(s => s.PrinterID == printer.PrinterID).Single();
                printerDB.PrinterName = printer.PrinterName;
                context.SaveChanges();
            }
            else
            {
                Printer newPrinter = new Printer()
                {
                    PrinterName = printer.PrinterName
                };
                context.Printers.Add(newPrinter);
                context.SaveChanges();
            }
        }

        RefreshPrintersGrid();
    }

我将后面代码中的DataGridComboBoxColumn绑定到包含打印机列表的EF模型。

选择该值并触发RowEditEnding函数时,组合框的值不会在FunctionPrinterLookupModel模型中更新。我觉得自己在这里陷入困境,还没有找到一个可以在我的谷歌搜索时间中起作用的解决方案。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

最好将组合框项目源绑定到ViewModel中的属性。然后绑定选定的打印机,并在ViewModel中更改属性时执行操作。

<DataGridComboBoxColumn x:Name="ddlPrinters" Header="Printer" Width="*" ItemsSource="{Binding PrinterList}"  SelectedItem="{Binding SelectedPrinter, Mode=TwoWay}" SelectedValuePath="PrinterID" DisplayMemberPath="PrinterName"/>

在ViewModel中

Private PrinterInfo _SelectedPrinter { get; set; }

Publuc PrinterInfo SelectedPrinter 
{
    get
    {
        return _SelectedPrinter;
    }  
    set
    {
        _SelectedPrinter = value;
        //save value to db or other actions
    }  
}
相关问题