我在 Windows 2012 中有一个 WPF 项目,我需要在 Window Loaded 事件中加载一些信息。不过,我需要在视图模型中而不是在 CodeBehind 中执行此操作。我正在尝试使用以下代码:
在我的 xaml 中:
<interactivity:Interaction.Behaviors>
<behaviors:WindowLoadedBehavior LoadedCommand="{Binding WindowLoadedCommand}" />
</interactivity:Interaction.Behaviors>
在我的视图模型中:
private DelegateCommand _WindowLoadedCommand;
public DelegateCommand WindowLoadedCommand
{
get
{
return _WindowLoadedCommand;
}
private set
{
_WindowLoadedCommand = value;
}
}
public ShellViewModel()
{
WindowLoadedCommand = new DelegateCommand(WindowLoadedAction);
}
protected void WindowLoadedAction()
{
...
}
我的附加行为:
public class WindowLoadedBehavior : Behavior<FrameworkElement>
{
[SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Dependency Property. Allow public.")]
public static DependencyProperty LoadedCommandProperty = DependencyProperty.Register("LoadedCommand", typeof(ICommand), typeof(WindowLoadedBehavior), new PropertyMetadata(null));
public ICommand LoadedCommand
{
get { return (ICommand)GetValue(LoadedCommandProperty); }
set { SetValue(LoadedCommandProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += AssociatedObject_Loaded;
}
protected override void OnDetaching()
{
AssociatedObject.Loaded -= AssociatedObject_Loaded;
base.OnDetaching();
}
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
if (LoadedCommand != null)
LoadedCommand.Execute(null);
}
}
OnAttached、AssociatedObject_Loaded 和 LoadedCommand get 都在触发,但 LoadedCommand 集没有触发,显然 WindowLoadedCommand 没有触发。任何线索我可以做些什么来让这个工作?