我创建了一个包含多行和多列的数据网格。其中一列是用户可以更改的字段大小列表。
我正在针对旧值检查新值,如果新值小于旧值,我告诉用户这是无效的,然后我想将旧值恢复并将焦点重置为该单元格。
我在LostFocus
事件中有这一行:
System.Windows.Controls.TextBox tbNewSize =
(System.Windows.Controls.TextBox)dtgCell.Content;
当我点击单元格时,LostFocus
事件被调用并且正常工作。但是,当我尝试重新聚焦到单元格时,我收到错误说
“无法将'System.Windows.Controls.TextBlock'类型的对象强制转换为'System.Windows.Controls.TextBox'。”
如何更正此问题?
这是我的XAML代码:
<DataGrid HeadersVisibility="Column" Name="dtGrid" Loaded="GridLoaded" AutoGenerateColumns="False" IsReadOnly="False" VirtualizingPanel.IsVirtualizing="False" Height="365" Width="530" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="54,74,0,0" BorderThickness="1,1,0,1" BorderBrush="Black">
<DataGrid.Columns>
<DataGridTextColumn Header="Field" Binding="{Binding Field, Mode=TwoWay}" Width="209" IsReadOnly="True" />
<DataGridTextColumn Header="Size" Binding="{Binding Size, Mode=TwoWay}" Width="89"/>
<DataGridCheckBoxColumn Header="Right Justify" Binding="{Binding RightJustify, Mode=TwoWay}" Width="55" />
<DataGridCheckBoxColumn Header="Left Justify" Binding="{Binding LeftJustify, Mode=TwoWay}" Width="55" />
<DataGridCheckBoxColumn Header="Left Zero Fill" Binding="{Binding LeftZeroFill, Mode=TwoWay}" Width="55" />
<DataGridCheckBoxColumn Header="Right Zero Fill" Binding="{Binding RightZeroFill, Mode=TwoWay}" Width="65" />
</DataGrid.Columns>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock TextWrapping="Wrap" Text="{Binding}"></TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="#FF9DF3D6" />
<Setter Property="Foreground" Value="#000000" />
</Trigger>
</Style.Triggers>
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown" />
<EventSetter Event="LostFocus" Handler="DataGridCell_OnCellLostFocus" />
</Style>
</DataGrid.Resources>
这是我的c#代码:
private void DataGridCell_OnCellLostFocus(object sender, RoutedEventArgs e)
{
System.Windows.Controls.DataGridCell dtgCell = (System.Windows.Controls.DataGridCell)sender;
if (dtgCell.Column.Header.ToString() == "Size")
{
System.Windows.Controls.TextBox tbNewSize = (System.Windows.Controls.TextBox)dtgCell.Content;
Int32 intNewSize = Convert.ToInt32(tbNewSize.Text);
Int32 intCurrSize = Convert.ToInt32(strFieldInfoOrig[dtGrid.Items.IndexOf(dtGrid.CurrentItem), 1]);
if (intNewSize < intCurrSize)
{
string strMsg;
strMsg = "New size, " + intNewSize.ToString() + " is smaller then the original size, " + intCurrSize.ToString();
strMsg += Environment.NewLine;
strMsg += "Due to potential data loss, this is not allowed.";
System.Windows.MessageBox.Show(strMsg);
//dtgCell.Content = intCurrSize.ToString();
dtgCell.Focus();
}
}
}
答案 0 :(得分:0)
这种情况正在发生,因为DataGridTextColumn
在正常模式下显示TextBlock
,在编辑时显示TextBox
。因此,当此单元格失去焦点时,DataGridTextColumn
将返回正常模式,因此其内容将为TextBlock
而不是TextBox
,因此它会显示异常。
因此,请尝试转换为TextBlock
而不是TextBox
。
答案 1 :(得分:0)
您可以处理CellEditEnding事件。
<DataGrid AutoGenerateColumns="False"
CellEditEnding="DataGrid_CellEditEnding"
...
>
<DataGrid.Columns>
<DataGridTextColumn Header="Size" Binding="{Binding Size, Mode=TwoWay}" .../>
...
</DataGrid.Columns>
...
</DataGrid>
背后的代码
private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
DataGrid datagrid = sender as DataGrid;
if (e.EditAction == DataGridEditAction.Commit)
{
if (e.Column is DataGridBoundColumn)
{
DataGridBoundColumn column = (DataGridBoundColumn)e.Column;
if (column.Header.ToString() == "Size")
{
string oldValue = e.Row.DataContext.GetType().GetProperty("Size")
.GetValue(e.Row.DataContext).ToString();
TextBox element = e.EditingElement as TextBox;
string newValue = element.Text;
int oldSize = int.Parse(oldValue);
int newSize = int.Parse(newValue);
if (newSize < oldSize)
{
string strMsg = "New size, " + newValue + ", is smaller then the original size, "
+ oldValue + ".\nDue to potential data loss, this is not allowed.";
MessageBox.Show(strMsg);
element.Text = oldValue;
e.Cancel = true;
}
}
}
}
}
设置e.Cancel = true
可使单元格保持编辑状态。
答案 2 :(得分:0)
您正在尝试将TextBlock
投射到TextBox
,这显然无效。但是,如果您只是尝试总是像这样投射到TextBlock
:
System.Windows.Controls.TextBlock tbNewSize = (System.Windows.Controls.TextBlock)dtgCell.Content;
......这也行不通。这是因为单元格的Content
可能是TextBox
或 a TextBlock
,具体取决于单元格当前是否处于编辑模式。
您可以使用as
运算符尝试转换为TextBox
,如果转换失败,则转换Content
属性到TextBlock
:
private void DataGridCell_OnCellLostFocus(object sender, RoutedEventArgs e)
{
System.Windows.Controls.DataGridCell dtgCell = (System.Windows.Controls.DataGridCell)sender;
if (dtgCell.Column.Header.ToString() == "Size")
{
string text = null;
System.Windows.Controls.TextBox tbNewSize = dtgCell.Content as System.Windows.Controls.TextBox;
if (tbNewSize != null)
{
text = tbNewSize.Text;
}
else
{
System.Windows.Controls.TextBlock tb = dtgCell.Content as System.Windows.Controls.TextBlock;
if (tb != null)
text = tb.Text;
}
Int32 intNewSize = Convert.ToInt32(text);
Int32 intCurrSize = Convert.ToInt32(strFieldInfoOrig[dtGrid.Items.IndexOf(dtGrid.CurrentItem), 1]);
if (intNewSize < intCurrSize)
{
string strMsg;
strMsg = "New size, " + intNewSize.ToString() + " is smaller then the original size, " + intCurrSize.ToString();
strMsg += Environment.NewLine;
strMsg += "Due to potential data loss, this is not allowed.";
System.Windows.MessageBox.Show(strMsg);
//dtgCell.Content = intCurrSize.ToString();
dtgCell.Focus();
}
}
}