You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio热重载后,自定义下拉控件命令绑定仅生效一次

下拉菜单控件热重载后命令绑定异常问题

控件依赖属性定义

public static readonly DependencyProperty DropDownCommandsDictProperty = DependencyProperty.Register(
        nameof(DropDownCommandsDict),
        typeof(ObservableCollection<Tuple<string, IAsyncRelayCommand>>),
        typeof(ToggleButtonDropDownControl),
        new FrameworkPropertyMetadata(
            new ObservableCollection<Tuple<string, IAsyncRelayCommand>>(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

public ObservableCollection<Tuple<string, IAsyncRelayCommand>> DropDownCommandsDict
{
    get => (ObservableCollection<Tuple<string, IAsyncRelayCommand>>)GetValue(DropDownCommandsDictProperty);
    set => SetValue(DropDownCommandsDictProperty, value);
}

控件结构与绑定设置

该控件通过ToggleButton和Popup展示命令列表:

  • 控件内部ListView绑定代码:
<ListView ItemsSource="{Binding Path=DataContext.RecipeDropDownCommandsDict, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}, AncestorLevel=1}}">
  • 控件使用代码:
<sharedControls:ToggleButtonDropDownControl 
    Caption="..."
    DropDownCommandsDict="{Binding Path=DataContext.RecipeDropDownCommandsDict, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}, AncestorLevel=1}}"
    CommandParameter="{Binding Path=.}"
    VerticalAlignment="Center" />

问题现象

  • 触发Visual Studio热重载后,命令绑定仅能生效一次
  • 将控件代码直接嵌入XAML文件时,命令执行完全正常

排查过程

遍历可视化树排查问题,发现下拉菜单位于可视化树底部,曾怀疑问题出在依赖属性定义中。

最终结论

确认是样式setter覆盖了可点击控件,导致其无法正常处理事件,热重载只是增加了调试难度。

内容的提问来源于stack exchange,提问作者Schnitzel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:37:13