您可以将按钮链接到Command,然后使用Command.Execute()从代码中的任何位置触发命令。伪代码:
XAML:
<UserControl x:Class="ClassName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:commands="clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation">
<Button commands:Click.Command="{Binding MyCommand}" />
</UserControl>
CODE(后面或MVVM):
public class ClassName
{
///Class constructor
public ClassName()
{ /// implement the command behaviour as a delegate
MyCommand = new DelegateCommand<object>(
delegate{
/// do your OnClick() behaviour implementation here
}
);
}
private DelegateCommand<object> _myCommand;
public DelegateCommand<object> MyCommand
{
get { return _myCommand; }
set { myCommand=value;
OnPropertyChanged("MyCommand");}
}
/// Another method called from somewhere else in code
void SomeOtherMethod()
{
MyCommand.Execute(null);
}
}
这工作特别好MVVM世界。
这个问题仍然存在于SL4(我怀疑SL5)。除了前面介绍的浏览器解决方案之外,我已经更新了我的答案,以包含浏览器外解决方案。 – 2012-03-16 00:39:03