窗口加载和WPF

Dir*_*dly 7 c# wpf events xaml mvvm

我在Windows 2012中有一个WPF项目,我需要在Window Loaded事件中加载一些信息.不过,我需要在View Model中而不是在CodeBehind中执行此操作.我试图使用以下代码:

在我的xaml中:

<interactivity:Interaction.Behaviors>
    <behaviors:WindowLoadedBehavior LoadedCommand="{Binding WindowLoadedCommand}" />
</interactivity:Interaction.Behaviors>
Run Code Online (Sandbox Code Playgroud)

在我的视图模型中:

private DelegateCommand _WindowLoadedCommand;

public DelegateCommand WindowLoadedCommand
{
    get
    {
        return _WindowLoadedCommand;
    }
    private set
    {
        _WindowLoadedCommand = value;
    }
}

public ShellViewModel()
{
    WindowLoadedCommand = new DelegateCommand(WindowLoadedAction);
}

protected void WindowLoadedAction()
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我附加的行为:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

OnAttached,AssociatedObject_Loaded和LoadedCommand get都被触发,但是LoadedCommand集没有触发,显然,WindowLoadedCommand没有触发.任何线索我能做些什么来使这个工作?

Har*_*ess 33

有几个选择.其中一些列在这里:

如何在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);
}
Run Code Online (Sandbox Code Playgroud)

  • 那太棒了!显然我遇到的问题是在加载窗口之前没有正确加载事件处理类.你的方法(以及简短和重点)避免了这种方法并允许它正确地触发. (2认同)