【发布时间】:2018-12-31 18:13:51
【问题描述】:
我有数据网格,其中项目源与数据库中的数据绑定。它有两个使用值转换器的有界值的数据模板。(我已经使用转换器将员工 ID(frow1 列)转换为图像路径)。现在我想展示当用户双击带有图像的单元格时的员工 ID。当我成功运行填充有员工图像的应用程序数据网格时。
到目前为止,我已经尝试使用 DataGridCellInfo,如下面的代码所示。我在数据网格 xamal 中设置了 CurrentCell="{Binding CellInfo, Mode=TwoWay}"。这里 CellInfo 是公共属性
<DataGrid x:Name="dtGrid" AutoGenerateColumns="False"
Margin="0,0,0,0" SelectionUnit="Cell"
HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"
SelectionMode="Single"
CurrentCell="{Binding CellInfo, Mode=OneWayToSource}"
VerticalAlignment="Top" RowHeight="50" ColumnWidth="50"
AlternatingRowBackground="{x:Null}" AlternationCount="2"
CanUserResizeRows="False" CanUserAddRows="False" CanUserDeleteRows="False"
CanUserReorderColumns="False" CanUserResizeColumns="False"
CanUserSortColumns="False" HeadersVisibility="None"
GridLinesVisibility="None" HorizontalGridLinesBrush="{x:Null}"
VerticalGridLinesBrush="{x:Null}" >
<DataGrid.Columns>
<DataGridTemplateColumn Width="SizeToCells" IsReadOnly="True" > <DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<Button Background="#FF1D5BBA"
PreviewMouseDoubleClick="Button_PreviewMouseDoubleClick" >
<Image Source="{Binding Path=frow1,
Converter=StaticResource
prfileconverter},
Mode=Default}" />
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我的代码:
private void Button_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
MessageBox.Show(CellInfo.ToString())
}
private DataGridCellInfo _cellInfo;
public DataGridCellInfo CellInfo
{
get {
return _cellInfo;
}
set
{
_cellInfo = value;
OnPropertyChanged("CellInfo");
//this is to refresh through INotifyPropertyChanged
}
}
在这里,当我在单元格上执行 MouseDoubleClick 时,我遇到了如何显示员工 ID 的问题。当我双击单元格时,我收到消息框说“System.Windows.Control.DataGridCellInfo”。我没有收到单元格项目(员工 ID)
【问题讨论】:
-
试试
CellInfo.Item.ToString() -
显示错误:未处理空引用异常
-
这里的 DataContext / ViewModel 是什么?
-
请记住,DataGridCellInfo 代表 row(以及绑定到该行的对象),而不是 cell 本身。
-
DataContext 在构造函数中给出:transportListDataView = loademp().DefaultView; dtGrid.ItemsSource = transportListDataView;