WPF Popup内绑定Command的Button始终禁用问题咨询
我实现了一个自定义ExButton,鼠标悬停时会显示通过属性传入的Popup内容,初始化代码如下:
//Creating the popup if there's a content to be displayed: _popup = new Popup { PlacementTarget = this, Placement = PlacementMode.Top, VerticalOffset = -5, StaysOpen = false, Child = PopupContent, AllowsTransparency = true, PopupAnimation = PopupAnimation.Fade, }; _popup.SetBinding(DataContextProperty, new Binding { Source = this, Path = new PropertyPath("DataContext") }); //Later, on hover: _popup.IsOpen = true;
目前Popup内绑定Window的ViewModel的Slider、TextBlock等控件均正常工作,但Button的Command始终无法解析,按钮保持禁用状态。以下是简化的音量弹出层示例代码:
<c:ExButton Command="{Binding ToggleMuteCommand}" Content="Volume"> <c:ExButton.PopupContent> <Border> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition/> <ColumnDefinition Width="34"/> </Grid.ColumnDefinitions> <c:ExButton Grid.Column="0" Content="Mute" Command="{Binding ToggleMuteCommand}" CommandTarget="{Binding ElementName=EditorWindow}"/> <Slider Grid.Column="1" Value="{Binding Volume, Mode=TwoWay}" Maximum="100"/> <TextBlock Grid.Column="2" Text="{Binding Volume, StringFormat=0}"/> </Grid> </Border> </c:ExButton.PopupContent> </c:ExButton>
命令在ViewModel中创建,并绑定到Window的CommandBindings:
new CommandBinding(_viewModel.ToggleMuteCommand, ToggleMute_Executed, _viewModel.HasProjectSoCanExecute),
经检查,Popup内的按钮始终处于禁用状态,其他绑定均正常。我已尝试以下方案但均无效:
- 为Popup设置Window的ViewModel作为DataContext,此时Command不再为null,但按钮仍禁用;
- 复用Window的CommandBindings或为Popup新建CommandBindings,无效果;
- 移除CanExecute回调,无变化;
- 将CommandTarget设置为Window、Button或ViewModel,均无改善。
现提出两个疑问:
- 为何DataContext为null时,命令绑定结果为null,但其他绑定仍能正常工作?
- Popup内的命令无法启用Button的原因是什么?
内容的提问来源于stack exchange,提问作者Nicke Manarin
相关产品推荐
相关产品推荐

