WPF MVVM - DataGrid 单元格单击,获取列标题
本文关键字:获取 标题 单击 单元格 MVVM DataGrid WPF | 更新日期: 2023-09-27 17:57:08
使用Prism框架实现WPF MVVM解决方案。
我想使用 DataGrid 或 GridView 显示表格数据。然后,当单击单元格时,它应该触发一个命令,并作为命令参数,列标题的标题。(仅适用于"借方和贷方"列,如下面的代码所示。代码最终要做的是,当单击"借方"字段时,"金额"将复制到该字段。如果随后在"贷方"字段中单击,则将清除"借方"字段,并将值复制到"贷方"字段中)
尝试了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>
试试这个。它应该很明显地工作。
if(AccountEntryDataGrid.SelectedCells.Count == 1)
{
var selectedColumnHeader =
AccountEntryDataGrid.SelectedCells[0].Column.Header.ToString();
}
哎呀。。。不好意思。。。刚才发现你正在使用 MVVM。将SelectedCells
作为命令参数传递。它应该是IList<DataGridCellInfo>
类型。针对 MVVM 相应地修改代码。也许是这样的。
private void OnClicked(IList<DataGridCellInfo> selectedCells)
{
if(selectedCells.Count == 1)
{
var selectedColumnHeader = selectedCells[0].Column.Header.ToString();
}
}
尝试两种方式。祝你好运。