您好,登錄后才能下訂單哦!
在打造CustomControl時(shí), 我們可能會(huì)遇到這樣的情況: 希望模板中的Button能執(zhí)行Control中某些特定的邏輯.
對(duì)于這種情況,有兩種解決方法:TemplatePartAttribute和Command.
TemplatePartAttribute就是對(duì)UI中的元素命名, 然后在后臺(tái)尋找此元素進(jìn)行相應(yīng)的操作. 很可惜, 這會(huì)使得UI與邏輯耦合, 這與CustomControl的初衷相悖.當(dāng)外部程序改寫(xiě)Template時(shí),很有可能失去作用.
而Command則十分可靠, 因?yàn)樗苁筓I和邏輯分離. 外部改寫(xiě)UI后, 只需對(duì)相應(yīng)的元素重新綁定內(nèi)置的Command就可以正常地工作. 下面為大家如何內(nèi)置Command和如何進(jìn)行綁定.
在下面的后臺(tái)代碼中, 對(duì)TestCommand進(jìn)行聲明和初始化. 然后在靜態(tài)構(gòu)造函數(shù)中通過(guò)CommandManager.RegisterClassCommandBinding(Type,CommandBinding)的方法進(jìn)行類綁定(當(dāng)然, 你也可以在構(gòu)造函數(shù)中使用公共的CommandBindings集合,但這并不可靠,因?yàn)樗耸褂么丝丶r(shí)可以隨意修改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() { } }
接下來(lái),看看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只需要這樣就可以對(duì)內(nèi)置的命令進(jìn)行綁定.
以上就是在CustomControl中內(nèi)置Command的方法.
PS: Button的Content不會(huì)自動(dòng)綁定RoutedUICommand中的Text屬性,可以將Content綁定Command.Text , 如下: Content="{Binding Path=Command.Text,RelativeSource={RelativeSource Self}}"
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。