I saw online 2 different approaches to enhancing an IValueConverter. One of them extended a ValueConverter from MarkupExtension, the other from DependencyObject. I can't extend from both, so I'm wondering if any one is better than the other?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Deriving from each gives you different kind of power and flexibility:
Deriving from
MarkupExtension
enables you to use the value converter without making it a static resource, as described below:In XAML, you can directly use it without creating a StaticResource:
Such code is very handy when debugging, as you can just write
local:DebugMe
and then can debug the DataContext of the control on which you use it.Deriving from
DependencyObject
enables you to configure the value converter with some preferences in a more expressive way, as described below:In XAML, you can directly use it as:
What does it do? It truncates the string
FullDescription
if it is more than50
characters!@crazyarabian commented that:
That is true. But then that is not bindable; that is, when you derive from
MarkupExtension
, then you cannot do :But if you derive your converter from
DependencyObject
, then you can do the above. In that sense, it is more expressive compared toMarkupExtension
.Note that the target property must be a
DependencyProperty
forBinding
to work. MSDN says,Since it's my library you're citing as an example of converters that extend
DependencyObject
, I think it fitting to explain myself.I actually started out by simply implementing
IValueConverter
withObject
as my base class. The only reason I switched to extendingDependencyObject
was to allow for a technique - pioneered by Josh Smith - called virtual branching. You can read about that technique here.Suppose you want to do something like this:
This won't work because resources are not part of the visual tree, and so the binding will fail. Virtual branching hacks around this little dilemma, enabling you to perform such a binding. However, it still relies - like any other WPF binding - on the target being a
DependencyObject
. Thus, if I simply implementedIValueConverter
without extendingDependencyObject
, you would be precluded from using virtual branches.Now, if I'm completely honest, I'm not sure I'd still do this if I had my time again. I've never actually had to use a virtual branch myself - I just wanted to enable the scenario. I may even change this in a future version of my library. So my advice would be stick to a base class of
Object
(or a simple derivative thereof) unless you really think you'll need virtual branching.