WPF - 自定义控件 + ICommand(如何实现)?
基本上,我有一个自定义控件 FooControl
。
public class FooControl : ItemsControl
{
//Code
}
我需要添加一些事件处理,但我更喜欢使用 Commanding,而不是使用 RoutedEvent。但我不太确定如何去做这件事。如果我想要它,那么当 Bar1Property (DependencyProperty) 更改时,它会引发 Execute 关联的执行属性。我通过 .NET Reflector 查看了 ButtonBase 代码,哇,这看起来太复杂了。添加命令这么复杂吗?显然,我还必须做到这一点,以便我的控件根据 CanExecuteChanged 是否更改来启用/禁用其自身的某些部分。但我想那是另一部分。
这是到目前为止我的 OnBar1Changed 函数......
private static void OnBar1Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
FooControl element = (FooControl)obj;
//What to do here?
}
Basically, I have a custom control FooControl
.
public class FooControl : ItemsControl
{
//Code
}
I need to add some event handling, but rather than using a RoutedEvent I'd much more prefer to use Commanding instead. I'm not really sure how to go about doing this though. If I want it so that when Bar1Property (DependencyProperty) changes it raises the Execute associated execute property. I looked at the ButtonBase code through .NET Reflector and wow, that looks overly complicated. Is adding a command this complex?? Obviously I'd also have to make it so that my control enables/disables certain parts of itself depending on if the CanExecuteChanged is altered or not. But I guess that's another portion.
Here is my OnBar1Changed function so far...
private static void OnBar1Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
FooControl element = (FooControl)obj;
//What to do here?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您提出问题的方式似乎是您希望在自定义控件中支持命令(例如按钮支持)。为此,我建议您查看 ICommandSource 的实现方式。 Microsoft 提供了有关如何自行实现它的精彩演练:
http://msdn .microsoft.com/en-us/library/ms748978.aspx
It sounds like by the way you are asking your question, you want to support commanding in your custom control (like for example Button supports). To do this you I recommend looking at how ICommandSource is implemented. Microsoft gives a great walk through on how you can implement it yourself:
http://msdn.microsoft.com/en-us/library/ms748978.aspx
在最简单的层面上,您真正需要的只是:
您还必须为 Command 和 CommandParameter 创建依赖项属性。
希望有帮助,
At the simplest level, all you really need is something like:
You'd have to create Dependency Properties for both the Command and the CommandParameter, as well.
Hope that helps,