将 C# 代码中的 StringFormat 应用到每个自定义文本框
我有继承自 WPF TextBox 的 MyTextBox 类,我在 XAML 代码中的任何地方都使用 MyTextBox,我想更新 MyTextBox C# 类,所以我最终在 UI 中的任何地方都在 MyTextBox 的 TextProperty 上应用了 StringFormat,所以我不必更新每个 MyTextBox出现在每个 XAML 文件中。
注意:我见过这样的东西
var oldBinding = this.GetBindingExpression(TextProperty)?
.ParentBinding;
if (oldBinding != null)
{
var newBinding = new Binding(oldBinding.Path.Path)
{
// copy everything from oldBinding
StringFormat = "MyStringFormat"; // set string format
};
this.SetBinding(TextProperty, newBinding);
}
但我认为为每个对象重置绑定对象两次是不合适的!我正在寻找更优雅、更高效的东西!
I have MyTextBox class that inherits from WPF TextBox, I am using MyTextBox everywhere in XAML code, I want to update MyTextBox C# class so I ended up with a StringFormat applied over MyTextBox's TextProperty everywhere in UI, so I do not have to update every MyTextBox occurrence in every XAML file.
Note: I have seen something like this
var oldBinding = this.GetBindingExpression(TextProperty)?
.ParentBinding;
if (oldBinding != null)
{
var newBinding = new Binding(oldBinding.Path.Path)
{
// copy everything from oldBinding
StringFormat = "MyStringFormat"; // set string format
};
this.SetBinding(TextProperty, newBinding);
}
But I think it is not proper to reset the binding object twice for every object! I am looking for something more elegant and efficient!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,由于您无法更改 XAML 标记中定义的密封绑定,因此您实际上必须创建一个新的绑定并替换现有的绑定。
另一个选项是编辑 XAML 文件并首先使用
StringFormat
定义正确的绑定。Well, since you cannot change a sealed binding that is defined in the XAML markup you actually have to create a new binding and replace the existing one.
The other option is to edit the XAML files and define the correct binding with the
StringFormat
in the first place.