7

我在 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 没有触发。任何线索我可以做些什么来让这个工作?

4

1 回答 1

36

有几个选项。这里列出了其中的几个:

如何在 WPF MVVM 中调用窗口的 Loaded 事件?

但是,如果您或其他任何人关心您要花费几个小时来完成本应花费 30 秒的任务,您可能想尝试一下。

public MainWindow()
{
    InitializeComponent();

    this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    ShellViewModel.Instance.WindowLoadedCommand.Execute(null);
}
于 2012-09-25T21:19:38.300 回答