CustomControl之内置命令

    在打造CustomControl时, 我们可能会遇到这样的情况: 希望模板中的Button能执行Control中某些特定的逻辑.

公司主营业务:网站设计、成都网站制作、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。成都创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。成都创新互联公司推出全州免费做网站回馈大家。

    对于这种情况,有两种解决方法:TemplatePartAttribute和Command.

    TemplatePartAttribute就是对UI中的元素命名, 然后在后台寻找此元素进行相应的操作. 很可惜, 这会使得UI与逻辑耦合, 这与CustomControl的初衷相悖.当外部程序改写Template时,很有可能失去作用.

    而Command则十分可靠, 因为它能使UI和逻辑分离. 外部改写UI后, 只需对相应的元素重新绑定内置的Command就可以正常地工作. 下面为大家如何内置Command和如何进行绑定.

    

    在下面的后台代码中, 对TestCommand进行声明和初始化. 然后在静态构造函数中通过CommandManager.RegisterClassCommandBinding(Type,CommandBinding)的方法进行类绑定(当然, 你也可以在构造函数中使用公共的CommandBindings集合,但这并不可靠,因为他人使用此控件时可以随意修改CommandBindings)

    public class CustomControl1 : Control
    {
        public static readonly RoutedUICommand TestCommand;
        
        static CustomControl1()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
            TestCommand = new RoutedUICommand("Test", "TestCommand", typeof(CustomControl1));
            CommandManager.RegisterClassCommandBinding(typeof(CustomControl1), new CommandBinding(TestCommand, TestExecute, TestCanExecute));
        
        }

        private static void TestCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            CustomControl1 c = sender as CustomControl1;
            if (c == null) return;
            e.CanExecute = c.CanExecute;
        }

        private static void TestExecute(object sender, ExecutedRoutedEventArgs e)
        {
            CustomControl1 c = sender as CustomControl1;
            if (c == null) return;

            Console.WriteLine("---TestCommand Executed---");
        }


        public bool CanExecute;

        public CustomControl1()
        {
           
        }

    }

    接下来,看看Generic.xaml中的UI代码:


    
        
            
                
                    
                        
                    
                
            
        
    

    在上面代码的Button中, Command只需要这样就可以对内置的命令进行绑定.

    以上就是在CustomControl中内置Command的方法.

PS: Button的Content不会自动绑定RoutedUICommand中的Text属性,可以将Content绑定Command.Text , 如下: Content="{Binding Path=Command.Text,RelativeSource={RelativeSource Self}}"


新闻标题:CustomControl之内置命令
本文链接:http://scyanting.com/article/ijccch.html