[英]WPF DataGrid - Iterating through rows and accessing control in template column
我來自ASP.NET背景,並且負責維護WPF項目,因此這是一個學習過程。
我有一個帶有以下XAML的DataGrid
<DataGrid Name="StockGV" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Scanned" IsReadOnly="true">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Name="StatusImage" Source="tick.png"></Image>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding PalletScanned}" Value="False">
<Setter TargetName="StatusImage" Property="Source" Value="cross.png"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Pallet Number" IsReadOnly="True" Binding="{Binding PalletNumber}">
</DataGridTextColumn>
<DataGridTextColumn Header="Quantity" IsReadOnly="True" Binding="{Binding Quantity}">
</DataGridTextColumn>
<DataGridTemplateColumn IsReadOnly="true">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<xctk:IntegerUpDown HorizontalAlignment="Left" Name="integerUpDown1" Maximum="{Binding Quantity}" Minimum="0" VerticalAlignment="Top" Value="{Binding Quantity, Mode=OneWay}" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding PalletScanned}" Value="False">
<Setter TargetName="integerUpDown1" Property="IsEnabled" Value="False"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
用戶更新最后一個字段(IntegerUpDown控件),然后單擊網格下方的“保存”按鈕。 我需要它來遍歷每一行,獲取IntegerUpDown控件的值並將其保存到數據庫。 如果這是ASP.NET,我將執行以下操作:
foreach (GridViewRow row in gv.Rows)
{
long pk = (long)gv.DataKeys[row.RowIndex].Value;
int value = (int)((IntegerUpDown)row.FindControl("integerUpDown1")).Value;
//Save to DB
}
我將如何在WPF中執行此操作? 請注意,如果有幫助,則將DataGrid綁定到匿名類型
哇,這不像它的本意是:)
通常,您應該將DataGrid
綁定到類型T的ItemsSource
。應該在列內部綁定到類型T的屬性。
然后,IntegerUpDown Control
上的每個更改都在基礎Collection中表示。
要稍后在ViewModel
訪問此值,您只需使用Linq查詢Collection
以獲取值。
您已經在控件中獲得以下代碼:
Value="{Binding Quantity, Mode=OneWay}"
因此,您可以訪問Quantity屬性以獲取所需的值。
請記住:如果用戶應該能夠更改Quantity Property
,則Binding
必須為Mode=TwoWay
並且該屬性也必須有一個公共設置器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.