DataGrid 中的自定义单击行为
我有一个显示自定义数据类型内容的数据网格。
<DataGrid Name="TestGrid" ItemsSource="{Binding Source={StaticResource Data}}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Value 1" Binding="{Binding Value1, StringFormat={}{0:C}}"/>
<DataGridTextColumn Header="Value 2" Binding="{Binding Value2, StringFormat={}{0:#.00}}"/>
</DataGrid.Columns>
我想将不同的命令绑定到每个 DataGridTextColumn 的 MouseLeftButtonDown 和 MouseRightButtonDown 事件。我可以使用 DataGridTemplateColumn 的 CellEditingTemplate 对输入进行一些自定义,但无法弄清楚如何获得我想要的行为。
编辑:我的目标是左键单击增加值,右键单击减少值,+/- 的大小会因列而异。
编辑2:似乎您可以使用触发器根据鼠标事件更改样式,但这似乎不适用于更改数据本身。我倾向于放弃数据网格并使用 ListView
I have a datagrid displaying the contents of a custom data type.
<DataGrid Name="TestGrid" ItemsSource="{Binding Source={StaticResource Data}}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Value 1" Binding="{Binding Value1, StringFormat={}{0:C}}"/>
<DataGridTextColumn Header="Value 2" Binding="{Binding Value2, StringFormat={}{0:#.00}}"/>
</DataGrid.Columns>
I want to tie different commands to the MouseLeftButtonDown and MouseRightButtonDown events for each DataGridTextColumn. I can use a DataGridTemplateColumn's CellEditingTemplate to do some customization of input, but haven't been able to figure out how to get the behavior I want.
Edit: What I'm aiming for is a left click increments the value and a right click decrements it, the size of the +/- would vary column to column.
Edit 2: It seems that you can change styles based on mouse events using triggers, but this doesn't seem to work for changing the data itself. I'm leaning towards abandoning the datagrid and going with a ListView
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是我对此主题的想法:
据我了解,您似乎不需要 dataGrid 中的任何编辑功能。在这种情况下,使用 ListView 确实会更好。
如果您想继续使用 dataGrid,最简单的方法确实是使用 TextBoxColumn.CellStyle 并在其中添加事件侦听器。如果您这样做,则必须确保在处理程序中更新 ViewModel 的值。
尝试这样的操作:
或者创建自己的
MyDataGridTextBoxColumn
类来继承原始类,并将样式添加到列的 xaml 定义中的列的 cellStyle 中。 (这样你就只有一个通用的代码部分)然后在处理程序中,你可以轻松地推断出你单击的单元格并相应地增加或减少 viewModel。
Here are my thoughts on the subject:
You do not seem to need any editing functionality in your dataGrid from what I understand. In this case, you would indeed be better off with a ListView.
If you want to continue with your dataGrid, the easiest way to do would indeed be to use TextBoxColumn.CellStyle and add the event listener there. If you do this, you'll have to make sure you update the ViewModel's value in your handler.
Try sompething like this:
or make your own
MyDataGridTextBoxColumn
class that inherits the original one, and add the style to the column's cellStyle in your column's xaml definition. (that way you have only one common portion of code)then in the handlers, you can easily deduce the cell where you clicked and increment or decrement the viewModel accordingly.