Are value converters instantiated per-binding in WPF?

混江龙づ霸主 提交于 2019-12-22 07:39:32

问题


Is a separate WPF value converter object instantiated for each binding that a particular value converter class is used in?


I am trying to create a two-way bit-to-boolean value converter. I would like to be able to bind a bool property (such as IsChecked) to a bit in a value type (like a ushort). I'm using the converter's parameter arguments to specify the bit. Implementing the ConvertBack() method is easy, but Convert() is little trickier.

In Convert() I need to know what the value of the entire ushort is so I can toggle just the single bit I am interested in. I was thinking of just using a member variable in my value converter class to temporarily store this whenever ConvertBack() is called, thus leading to the above question: does each binding get its own value converter instance?


回答1:


If you use a converter defined in your resources, it will be shared amongst your properties.

If you need unique converters: If you create a specific converter for a property, however, it will not be shared. Either option is workable. You can even use multiple converters (of the same type, with different keys) in your resources, which will create unique instances.




回答2:


Create a constructor and destructor in your converter and set breakpoints within to tell for sure. I just created a simple example and it looks like only one converter was created for my multiple viewmodels that were using the constructor



来源:https://stackoverflow.com/questions/2067527/are-value-converters-instantiated-per-binding-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!