WPF自定义按钮编程绑定默认CommandProperty不触发Execute问题
问题根因
你的自定义按钮InLineButtonControl本身已经继承自Button类,但在其内部XAML中额外嵌套了一层子Button。你给外层InLineButtonControl赋值的Command没有和实际响应点击事件的内层Button关联,点击操作被内层Button拦截,外层控件的Command自然不会触发。你不需要额外声明自定义的Command依赖属性,继承的默认CommandProperty完全可用,只需要修正控件结构或绑定关系即可。
解决方案
方案1:删除冗余的内层Button(推荐)
直接使用父控件本身的属性配置,不需要嵌套多余的Button,修改自定义控件的XAML代码如下:
<Button x:Class="MyResources.Recursos.Controles.Controls.InLineButtonControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:MyResources.Recursos.Controles.Controls" mc:Ignorable="d" d:DesignHeight="450" x:Name="ThisInlineButton" Style="{DynamicResource InLineButton}" d:DesignWidth="800"> <Button.ContentTemplate> <DataTemplate> <Image x:Name="BtnImage" Style="{DynamicResource ButtonImage}" Source="{Binding ElementName=ThisInlineButton,Path=ImageSource,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"/> </DataTemplate> </Button.ContentTemplate> </Button>
修改后你原来的动态生成按钮、赋值Command的代码不需要做任何改动,点击即可正常触发Execute。
方案2:保留内层Button时补全绑定
如果出于特殊需求必须保留内层嵌套的Button,需要将外层控件的Command、CommandParameter绑定到内层Button的对应属性上,修改内层Button的XAML代码:
<Button Style="{DynamicResource InLineButton}" Command="{Binding Command, RelativeSource={RelativeSource AncestorType=local:InLineButtonControl}}" CommandParameter="{Binding CommandParameter, RelativeSource={RelativeSource AncestorType=local:InLineButtonControl}}"> <!-- 原有ContentTemplate内容保持不变 --> </Button>
内容的提问来源于stack exchange,提问作者Juan Pablo Gomez
相关产品推荐
相关产品推荐

