从WPF的AttachProperty到Sliverlight3中的Behavior

                                                     周银辉 

 

  说来很巧,最早接触到Behavior模式不是在Sliverlight中,而是我们在使用“Prism+MVVM”试图将界面和后台逻辑尽可能脱耦时,那时我们发现虽然WPF的Command、Prism的DelegateCommand能很好地帮助我们脱耦,但WPF的Command数量太少(比如Button的Command对应的是Click事件,但如果我需要在Loaded时也使用Command,其就无能为力了),于是我们用到了一个称为Behavior的模式来协助我们解决,不过当时我们总习惯哈哈大笑,因为我们认为这是一个很龌龊的技巧。如果还要向前追溯的话,那就得到很久以前了,当时我发现WPF拥有一个能力是将某个属性“附加(Attach)”到某个对象上,也就是Attach Property,那么我们能否用相同的原理将某个功能也附加到某个的对象上呢?可以的,这就是Attached Behavior,在当时我一直觉得这仅仅是一个小技巧,因为我从来只用它来为同事的代码增加功能或修改Bug,同事在用我写的功能函数时,感觉是在给对象打插件,非常方便。前几天,听说MS将其纳入到Sliverlight3中了,颇感惊异。

 

1,从Attach属性开始 

 

在继续阅读之前,建议下载Demo程序,并先看看源代码

 

    <StackPanel Orientation="Vertical">
        
<Button x:Name="btn1" Content="I'm btn 1" 
                loc:InfoService.Info
="hahaha, I'm btn 1"  
                Click
="ShowInfo"/>
        
<Button x:Name="btn2" Content="I'm btn 2" 
                loc:InfoService.Info
="hehehe, I'm btn 2"  
                Click
="ShowInfo"/>
    
</StackPanel>

 从上面的代码看,你是不是可以猜到loc:InfoService.Info是一个AttachProperty,我们将一个字符串Attach到了一个Button控件上。恩,你的猜想是可行的,也是一般做法,但这里我们并不想这么做,看看我是怎么做的:

    public static class InfoService
    {
        
private static Hashtable infoCache = new Hashtable();

        
public static void SetInfo(Object obj, Object info)
        {
            
if (infoCache.Contains(obj))
            {
                infoCache[obj] 
= info;
            }
            
else
            {
                infoCache.Add(obj, info);
            }
        }     

        
public static Object GetInfo(Object obj)
        {
            
if (infoCache.Contains(obj))
            {
                Console.WriteLine(
"get value from custom cache");
                
return infoCache[obj];
            }

            
return null;
        }

                          
    }

相关文章: