您可以將按鈕鏈接到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