我有一個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不會觸發。任何線索我可以做些什麼來得到這個工作?
你沒有直接綁定到命令的任何特定原因? –
從我讀到的,直接綁定窗口加載事件不起作用的原因。 –