新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

CustomControl之内置命令-创新互联

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

我们提供的服务有:成都做网站、成都网站建设、微信公众号开发、网站优化、网站认证、颍上ssl等。为1000多家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的颍上网站制作公司

    对于这种情况,有两种解决方法: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}}"

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


新闻标题:CustomControl之内置命令-创新互联
链接URL:http://www.wjwzjz.com/article/diched.html
在线咨询
服务热线
服务热线:028-86922220
TOP