2

我将 TextBox 的文本绑定到 ViewModel 类中的一个属性,如下所示:

Text="{Binding Display, Mode=OneWay}"

问题是我需要在不更改 ViewModel 中的支持 Display 属性的情况下格式化 TextBox 的文本(我需要保持字符串的精度)。我可以在 ViewModel 中创建另一个属性,但在 View 类中更改它对我来说似乎更干净一些。问题是,第一次从 View 类更新 Text 后,数据绑定丢失,并且没有进一步的更新发生。

如何在操作 Text 属性后恢复数据绑定,为下一次 Display 属性更改做好准备?

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        const int maxForDisplay = 12;
        TextBox _display = sender as TextBox;
        if (_display.Text.Length > maxForDisplay)
        {
            _display.Text = _display.Text.Substring(0, maxForDisplay);
        }
    }
4

1 回答 1

4

你不应该做那样的事情。

如果您需要以format不同方式在 TextBox 中输出 - 使用Converter, 例如

Text="{Binding Display, Mode=OneWay, Converter={StaticResource myconverter}}"  

(转换器还支持转换back,因此将您输入的值转换为 Display - 例如,不确定这是否是您想要的,但您可以在输出到屏幕时添加额外的格式,并在“存储”回属性时将其删除)

或者,如果可能的话,只需使用{Binding Display, StringFormat=...}"

于 2013-04-21T17:31:26.920 回答