将 C# 代码中的 StringFormat 应用到每个自定义文本框

发布于 2025-01-12 22:25:36 字数 618 浏览 3 评论 0原文

我有继承自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清泪尽 2025-01-19 22:25:36

...但我认为为每个对象重置绑定对象两次是不合适的!

好吧,由于您无法更改 XAML 标记中定义的密封绑定,因此您实际上必须创建一个新的绑定并替换现有的绑定。

另一个选项是编辑 XAML 文件并首先使用 StringFormat 定义正确的绑定。

... but I think it is not proper to reset the binding object twice for every object!

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文