1
使用Prism框架實現WPF MVVM解決方案。WPF MVVM - DataGrid Cell單擊,獲取列標題
我想顯示錶格數據,使用DataGrid或GridView。 然後單擊單元格時,它應該觸發Command和CommandParameter,即ColumnHeader的標題。 (僅用於借記&信用列,如下面的代碼所示)代碼最終會做的是當點擊借記字段時,金額將被複制到該字段中。如果在信用字段中單擊,則借記字段將是清除並將值複製到信用字段中)
嘗試DataGrid,並且只管理將所選記錄傳遞迴ViewModel。 使用GridView,只管理一個命令到GridViewColumn標題。
任何幫助將不勝感激。
目前,這是我的代碼如下所示:
視圖模型:
public AccountingViewModel(IAccountingView view, IRegionManager manager, IEventAggregator eventAggregator)
:base(view, manager, eventAggregator)
{
AccountingEntries = new ObservableCollection<AccountingModel>();
FieldClickedCommand = new DelegateCommand<string>(OnClicked);
}
private void OnClicked(string column)
{
//Update corresponding field in record clicked cell
}
private AccountingModel _selectedAccount;
public AccountingModel SelectedAccount
{
get { return _selectedAccount; }
set
{
_selectedAccount = value;
OnPropertyChanged("SelectedAccount");
}
}
private ObservableCollection<AccountingModel> _accountingEntries;
public ObservableCollection<AccountingModel> AccountingEntries
{
get { return _accountingEntries; }
set
{
_accountingEntries = value;
OnPropertyChanged("AccountingEntries");
}
}
查看:
<Grid x:Name="AccountingViewModelLevel">
<DataGrid Grid.Row="1"
ItemsSource="{Binding AccountingEntries}"
SelectedItem="{Binding SelectedAccount}"
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserResizeColumns="False"
CanUserReorderColumns="False"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
SelectionMode="Single"
x:Name="AccountEntryDataGrid">
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick"
Command="{Binding FieldClickedCommand}"
CommandParameter="{Binding ElementName=AccountEntryDataGrid, Path=SelectedItem}" />
</DataGrid.InputBindings>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}" Header="No."/>
<DataGridTextColumn Binding="{Binding AccountName}" Header="Account Name"/>
<DataGridTextColumn Binding="{Binding Amount, StringFormat=0.00;;#}"
Header="Amount"
Width="90" />
<DataGridTextColumn Binding="{Binding Debit, StringFormat=0.00;;#}"
Header="Debit"
Width="90"
CellStyle="{StaticResource TrialBalanceStyle}"
>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Credit, StringFormat=0.00;;#}"
Header="Credit"
Width="90"
CellStyle="{StaticResource TrialBalanceStyle}"
IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
謝謝! 使用您的代碼,在視圖上只需在DataGrid上設置SelectionUnit =「Cell」並手動更新選擇的記錄。 –