WPF DataGridComboBoxColumn绑定

问题描述 投票:0回答:1

我在尝试使用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模型中更新。我觉得我喜欢把自己绑在这里,并且找不到可以通过我的谷歌搜索工作的解决方案。任何人都可以帮我理顺吗?

wpf datagridcomboboxcolumn
1个回答
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
    }  
}
© www.soinside.com 2019 - 2024. All rights reserved.