【发布时间】:2019-04-17 20:44:55
【问题描述】:
我从Microsoft Examples 中找到了一个自定义路由命令示例,它运行良好。
<Window x:Class="CustomRoutedCommand.MainWindow"
...
xmlns:local="clr-namespace:CustomRoutedCommand">
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:MainWindow.ColorCmd}"
Executed="ColorCmdExecuted"
CanExecute="ColorCmdCanExecute"/>
</Window.CommandBindings>
void ColorCmdExecuted(object sender, ExecutedRoutedEventArgs e)、void ColorCmdCanExecute(object sender, CanExecuteRoutedEventArgs e) 在 MainWindow.cs 中定义。
如果我将这两个处理程序移动到 xxxx.cs,如何更改 XAML?
编辑,添加更多信息
命令处理程序在MainWindow.cs中定义,我将代码剪切并粘贴到另一个文件中,如下所示,然后编译出错。 错误 CS1061“MainWindow”不包含“ColorCmdExecuted”的定义
// xxxx.cs
namespace CustomRoutedCommand
{
public class xxxx
{
// ExecutedRoutedEventHandler for the custom color command.
private void ColorCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
var target = e.Source as Panel;
if (target != null)
{
target.Background = target.Background == Brushes.AliceBlue ? Brushes.LemonChiffon : Brushes.AliceBlue;
}
}
// CanExecuteRoutedEventHandler for the custom color command.
private void ColorCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Source is Panel)
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
}
}
【问题讨论】:
-
您确定要使用
Static命令吗?并且来质疑你可以移动它是问题吗? -
实际上不确定,我是 WPF 初学者。我接受任何更好的建议。而且,当我将“ColorCmdExecuted”移动到另一个文件时出现错误。 错误 CS1061“MainWindow”不包含“ColorCmdExecuted”的定义
-
也可以发布移动的文件。我的意思是你把那个文件代码放在哪里。
-
在同一个命名空间下新建一个类(xxxx.cs),从MainWindow.cs中剪切代码并粘贴到xxxx.cs中。
-
您能从新文件中发布更多代码吗?特别是,这些命令仍然是
MainWindow的一部分,还是您定义了一个完全不同的类?