【发布时间】:2020-11-12 03:32:59
【问题描述】:
我正在使用两个文本框和“保存”按钮。基本上,当 TextBox 更改任何文本时,将启用“保存”按钮。我在Window.Resource 中创建了一个CommandBinding,并且“保存”Button 使用Command="Save" 和两个TextBox 使用StaticResources 进行命令绑定。
但是,当我更改文本时,按钮未启用。使用调试,我可以看到我的 TextBox 文本更改的标志是 True 但看起来 TextBox 没有触发 Save 命令 CanExecuted 事件。
下面是我的代码。
xaml
<Window>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.New" Executed="NewCommand_Executed" />
<CommandBinding Command="{x:Static commands:DataCommands.Requery}" Executed="RequeryCommand_Executed"/>
<CommandBinding Command="{x:Static commands:DataCommands.ApplicationUndo}"
Executed="ApplicationUndo_OnExecuted" CanExecute="ApplicationUndo_OnCanExecute"/>
</Window.CommandBindings>
<Window.Resources>
<CommandBinding x:Key="Binding" Command="ApplicationCommands.Save"
Executed="SaveCommand_Executed" CanExecute="SaveCommand_CanExecute"/>
</Window.Resources>
<StackPanel>
<Menu>
<MenuItem Header="File">
<MenuItem Command="New"/>
</MenuItem>
</Menu>
<StackPanel Orientation="Horizontal" Margin="5">
<Button Name="New" Command="New" Content="New" Margin="3" Padding="3"/>
<Button Name="Save" Command="Save" Content="Save" Margin="3" Padding="3"/>
...
</StackPanel>
<TextBox Name="TbInputText1" TextChanged="TbInputText_OnTextChanged" Margin="5">
<TextBox.CommandBindings>
<StaticResource ResourceKey="Binding"/>
</TextBox.CommandBindings>
</TextBox>
<TextBox Name="TbInputText2" Margin="5" TextChanged="TbInputText_OnTextChanged">
<TextBox.CommandBindings>
<StaticResource ResourceKey="Binding"/>
</TextBox.CommandBindings>
</TextBox>
<ListBox Name="LsbHistory" DisplayMemberPath="Name" Margin="3"></ListBox>
</StackPanel>
代码后面
public partial class UseCommand : Window
{
private Dictionary<Object, bool> _isDirty = new Dictionary<Object, bool>();
public UseCommand()
{
InitializeComponent();
this.AddHandler(CommandManager.PreviewExecutedEvent,
new ExecutedRoutedEventHandler(CommandExecuted));
}
private void TbInputText_OnTextChanged(object sender, TextChangedEventArgs e)
{
// _isDirty.Add(sender, true);
_isDirty[sender] = true;
}
#region Save
private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (_isDirty.ContainsKey(sender) && _isDirty[sender])
{
e.CanExecute = true;
}
else
{
// MessageBox.Show(sender.ToString());
e.CanExecute = false;
}
}
private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
string text = ((TextBox)sender).Text;
MessageBox.Show("About this controller: " + sender.ToString() +
"Contents: " + text);
_isDirty[sender] = false;
}
#endregion
}
我错过了什么步骤吗?为什么CanExecuted没有被触发?
【问题讨论】: