Tôi có một dự án WPF trong Windows 2012, trong đó tôi cần tải một số thông tin trong sự kiện Window Loaded. Tôi cần phải làm điều này trong Xem Model hơn là trong CodeBehind, mặc dù. Tôi đang cố gắng sử dụng đoạn mã sau:Window Loaded và WPF
Trong XAML của tôi:
<interactivity:Interaction.Behaviors>
<behaviors:WindowLoadedBehavior LoadedCommand="{Binding WindowLoadedCommand}" />
</interactivity:Interaction.Behaviors>
Trong Xem các mẫu của tôi:
private DelegateCommand _WindowLoadedCommand;
public DelegateCommand WindowLoadedCommand
{
get
{
return _WindowLoadedCommand;
}
private set
{
_WindowLoadedCommand = value;
}
}
public ShellViewModel()
{
WindowLoadedCommand = new DelegateCommand(WindowLoadedAction);
}
protected void WindowLoadedAction()
{
...
}
hành vi gắn My:
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);
}
}
Các OnAttached, AssociatedObject_Loaded và LoadedCommand nhận được là tất cả bắn, nhưng LoadedCommand thiết lập không phải là bắn và, rõ ràng , WindowLoadedCommand không kích hoạt. Bất kỳ đầu mối những gì tôi có thể làm để có được điều này làm việc?
Bất kỳ lý do cụ thể nào mà bạn không ràng buộc lệnh trực tiếp? –
Từ những gì tôi đã đọc, ràng buộc sự kiện Window Loaded trực tiếp không hoạt động vì một lý do nào đó. –