Reputation: 125
I'm using Caliburn.Micro
and have a DataGrid
. To fill the DataGrid
, a DataTable
is used.
For instance, I have three columns:
COL ID | COL NAME | COL NAME2
If the user clicks on any cell within the ID
column, I want an event to be triggered and want to get the Cell's containing text (in order to proceed any further).
However, I couldn't find anything on the Internet and am pretty baffled with this.
Upvotes: 1
Views: 410
Reputation: 556
While this is an old question, I was trying to do the same thing today and ran across it and ran into the same issue. The answer @mm8 gave didn't quite work because it puts the function in the code behind for the xaml document breaking MVVM that caliburn micro wants.
The following code works with MVVM, (although it feels like there should be an easier method, I haven't found one that targets individual cells rather than rows.)
I have the following defined at the window level in my xaml:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:cal="http://www.caliburnproject.org"
Then the datagrid becomes:
<DataGrid x:Name="yGrid" CanUserAddRows="False" IsReadOnly="True" SelectionUnit="Cell">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedCellsChanged">
<cal:ActionMessage MethodName="MyGridCellClicked">
<cal:Parameter Value="{Binding SelectedCells, ElementName=MyGrid}"/>
</cal:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
Then in the viewmodel:
public void MyGridCellClicked(IEnumerable<DataGridCellInfo> cells)
{
var info = cells.First();
if(info.Column.Header as string == "id")
{
MessageBox.Show(((System.Data.DataRow)info.Item)["id"].ToString());
}
}
Upvotes: 0
Reputation: 169390
You could handle the PreviewMouseLeftButtonDown event for the DataGridCell and access its Content property. The following code sample should give you the idea.
<DataGrid>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="dg_PreviewMouseLeftButtonDown" />
</Style>
</DataGrid.CellStyle>
</DataGrid>
private void dg_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
TextBlock tb = cell.Content as TextBlock;
if (tb != null)
{
MessageBox.Show(tb.Text);
}
}
Upvotes: 1