Reputation: 79
I am editing a textcell in a datagrid and I would like to get the selected text inside the datagrid cell text. Is there an event for it? The target is to find out the meaning of the selected text and show the ToolTip with the meaning. See the picture
<DataGrid x:Name="dgMeanings" Grid.Row="5" FontSize="16" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" RowEditEnding="dgMeanings_RowEditEnding" PreviewKeyDown="dgMeanings_PreviewKeyDown" AddingNewItem="dgMeanings_AddingNewItem" Background="{Binding ButtonBackColor}" Foreground="{Binding TextForeColor}" SelectionChanged="txt_SelectionChanged" CellEditEnding="dgMeanings_CellEditEnding" >
<DataGrid.Columns>
<DataGridTextColumn Header="#" Binding="{Binding IORDER,UpdateSourceTrigger=LostFocus}" Width="30"/>
<DataGridTextColumn Header="LEVEL" Binding="{Binding LEVEL,UpdateSourceTrigger=LostFocus}" Width="50"/>
<DataGridTextColumn Header="AS" Binding="{Binding TYPE ,UpdateSourceTrigger=LostFocus}" Width="60" />
<DataGridTextColumn Header="MEANING" Binding="{Binding MEANING ,UpdateSourceTrigger=LostFocus}" Width="400" />
<DataGridTextColumn Header="TRANSLATION" Binding="{Binding TRANSLATION ,UpdateSourceTrigger=LostFocus}" Width="150" />
<DataGridTextColumn Header="EXAMPLE" Binding="{Binding EXAMPLE,UpdateSourceTrigger=LostFocus}" Width="400"/>
<DataGridTextColumn Header="EXAMPLE TRANSLATION" Binding="{Binding EXAMPLE_TRANSLATION,UpdateSourceTrigger=LostFocus}" Width="400"/>
</DataGrid.Columns >
<DataGrid.Resources>
<Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="Black" />
</Style>
</DataGrid.Resources>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="{Binding LabelForeColor}"/>
</Style>
</DataGrid.RowStyle>
</DataGrid>
Upvotes: 0
Views: 332
Reputation: 323
C# Code
private void dgMeanings_Clicked(object sender, SelectedCellsChangedEventArgs e)
{
// Make sure at least 1 cell was selected
if (dgMeanings.SelectedCells.Count > 0)
{
// Get text from cell by getting the cell content at the selected cell's index
// Next, convert it to a TextBox and grab the text from the TextBox
string myText = ((TextBox)dgMeanings.SelectedCells[0].Column.GetCellContent(dgMeanings.SelectedCells[0].Item)).SelectedText;
// Unselect cells to allow for a re-click
dgMeanings.UnselectAllCells();
}
}
XAML
Add SelectedCellsChanged="dgMeanings_Clicked"
to your DataGrid
definition
Let me know if this doesn't work as expected or if you have any questions
Upvotes: 0