WPF按钮不响应任何事件
本文关键字:事件 任何 不响应 按钮 WPF | 更新日期: 2023-09-27 18:06:54
我有一个简单的WPF窗口,非常简单,TextBlock
和Button
。然而,按钮对任何东西都没有反应。如果我把鼠标移到它上面或者点击它。
按钮行:
<Button Margin="3" Command="Close" Content="Ok" Width="50"/>
完整窗口代码:
<Window x:Class="Launcher.XAML.MessageWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="self"
Title="{Binding ElementName=self, Path=Caption}" Height="194" Width="477">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Text="{Binding ElementName=self, Path=Message}" Margin="10" TextWrapping="Wrap" />
<StackPanel Grid.Row="1" HorizontalAlignment="Right" Orientation="Horizontal">
<Button Margin="3" Command="Close" Content="Ok" Width="50"/>
</StackPanel>
</Grid>
你需要像这样指定你的commandbinding和Button:
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close"
Executed="CloseCommandHandler"
CanExecute="CanExecuteHandler"
/>
</Window.CommandBindings>
....
<Button Margin="3" Command="ApplicationCommands.Close" Content="Ok" Width="50"/>
然后设置你的执行和CanExecute处理程序:
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
//Do something
}
private void CanExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
{
//Determine whether handler can execute
e.CanExecute = true;
}
这完全取决于style .xaml中的内容。试着把它注释掉,看看是否能正常工作。
与Close命令的绑定可能有问题。要看的东西(或者给我们看):
- 视图的DataContext设置正确
- 视图模型中Close属性返回的命令是如何实现的…