在打造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>
以上就是在CustomControl中内置Command的方法.
PS: Button的Content不会自动绑定RoutedUICommand中的Text属性,可以将Content绑定Command.Text , 如下: Content="{Binding Path=Command.Text,RelativeSource={RelativeSource Self}}"
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。