2012-09-25 85 views
6

我有一個WPF項目在Windows 2012中,我需要加載窗口加載事件中的一些信息。不過,我需要在視圖模型中而不是在CodeBehind中執行此操作。我嘗試使用下面的代碼:窗口加載和WPF

在我的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

從我讀到的,直接綁定窗口加載事件不起作用的原因。 –

回答

28

有幾個選項。他們夫婦這裏列出:

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); 
} 
+2

那很完美!顯然我遇到的問題是事件處理類在加載窗口之前未正確加載。你的方法(以及簡短的點)避免了這一點,並允許它正確地發射。 –