窗口加载和WPF

时间:2012-09-25 19:27:48

标签: 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>

在我的视图模型中:

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没有触发。任何线索我能做些什么才能让它发挥作用?

1 个答案:

答案 0 :(得分:32)

有几个选择。其中有几个列在这里:

how to call a window's Loaded event in WPF MVVM?

但是,如果您或其他任何人担心您花费几个小时完成一项应该花费30秒的任务,那么您可能希望尝试这样做。

public MainWindow()
{
    InitializeComponent();

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

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    ShellViewModel.Instance.WindowLoadedCommand.Execute(null);
}