WPF:需要TextBox才能拥有DataGrid单元格的一些高级功能

时间:2013-12-15 21:40:03

标签: c# wpf datagrid wpf-controls

我的应用程序实现了一个简单的计算链,就像电子表格一样。它有一个TextBox用户输入一些数值,一旦编辑,代码就会继续更新所有相关字段。

我对TextBox的稀缺经历告诉我,每次用户点击一个角色时都会触发一个事件。这种行为并不好:假设该人输入值" 1234":计算链将执行" 1",接下来执行" 12",然后执行" 123"最后是" 1234"。

我需要一种方法来了解编辑何时结束。也许矩形可能会在 Enter 时变为蓝色,就像DataGrid中的那些一样。用户应该可以使用标签键或点击其他位置离开。

另外:一个空的TextBox与包含零的东西不同!空TextBox的内容应该被识别为未定义。

问题是:我需要什么样的控制和辅助功能?

TIA。

1 个答案:

答案 0 :(得分:1)

听起来你只想在 TextBox LostFocus

时执行计算

在您的视图中,您将拥有

<Window...>

    <TextBox LostFocus="Perform_Calculation"/>

</Window>

然后在你的代码隐藏中定义该方法

private void Perform_Calculation(object sender, RoutedEventArgs e)
{
    // calculation logic here...
    // probably also where you will check if the Text is empty (nothing to be done)
}

或者,你可以使用TwoWay绑定, TextBox 上的默认 PropertyChangeTrigger 应该是 LostFocus - 所以你应该只获得你的财产当用户离开TextBox时更新。

请注意,这不会满足您在按 Enter 时处理它的希望,因为 TextBox 仍然会有焦点。要启用此功能,请稍微扩展

<Window...>

    <TextBox LostFocus="Perform_Calculation" KeyDown="TextBox_KeyDown"/>

</Window>

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        // perform calculation here (probably method that you will also call
        // from LostFocus handler to avoid duplication)
    }
}
相关问题