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代碼:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfCustomControlLibrary1">
    <Style TargetType="{x:Type local:CustomControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Button Command="local:CustomControl1.TestCommand"  Content="abc"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

    在上面代碼的Button中, Command只需要這樣就可以對內置的命令進行綁定.

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

PS: Button的Content不會自動綁定RoutedUICommand中的Text屬性,可以將Content綁定Command.Text , 如下: Content="{Binding Path=Command.Text,RelativeSource={RelativeSource Self}}"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章