在 WPF 中使用值转换器而不必先将它们定义为资源 [英] Using Value Converters in WPF without having to define them as resources first

查看:17
本文介绍了在 WPF 中使用值转换器而不必先将它们定义为资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用值转换器而无需事先将它们定义为资源?

Is it possible to use value converters without having to define them beforehand as resources?

现在我有

<Window.Resources>
    <local:TrivialFormatter x:Key="trivialFormatter" />
</Window.Resources>

<Button Width="{Binding Width, 
               ElementName=textBox1, 
               UpdateSourceTrigger=PropertyChanged, 
               Converter={StaticResource trivialFormatter}}">

难道不是我不必在 Window.Resources 中声明 trivialFormatter 资源,而是直接从 Button 的宽度绑定中引用它吗?类似的东西

Wouldn't it be possible that instead of having to declare the trivialFormatter resource in Window.Resources, I could directly refer it from the Button's width binding? Something like

Converter = {local:TrivialFormatter}

谢谢

推荐答案

在单例类型 IValueConverter 的情况下(例如,它们不需要来自当前绑定实例的任何状态)我使用静态转换器,即:

In the case of singleton-type IValueConverters (e.g. they don't need any state from the current binding instance) I use static converters, i.e.:

Converter={x:Static SomeNamespace:SomeConverter.Instance}

WPF 博士还发表了一篇关于使用标记扩展使其更清晰的内联文章 此处.

There's also a great post by Dr. WPF on using a markup extension to make it cleaner inline here.

这篇关于在 WPF 中使用值转换器而不必先将它们定义为资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆