Выполнить команду Silverlight 4 при загрузке - PullRequest
3 голосов
/ 23 апреля 2010

Как реализовать команду Silverlight 4, выполняемую при загрузке пользовательского элемента управления вместо привязки к явному нажатию кнопки?

Ответы [ 3 ]

4 голосов
/ 23 апреля 2010

Или просто добавьте триггер в xaml для вашего UserControl:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <si:InvokeDataCommand Command="{Binding MyCommand}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
1 голос
/ 19 февраля 2011

Это загрузка кода. Краткая версия без кода

public class LoadedBehaviour
{
   public static ICommand GetLoadedCommand(DependencyObject dependencyObject)
   {
      return (ICommand)dependencyObject.GetValue(LoadedCommandProperty);
   }

   public static void SetLoadedCommand(DependencyObject dependencyObject, ICommand value)
   {
      dependencyObject.SetValue(LoadedCommandProperty, value);
   }

   public static Action GetLoadedCommandExecutor(DependencyObject dependencyObject)
   {
      return (Action)dependencyObject.GetValue(LoadedCommandExecutorProperty);
   }

   public static void SetLoadedCommandExecutor(DependencyObject dependencyObject, Action value)
   {
      dependencyObject.SetValue(LoadedCommandExecutorProperty, value);
   }

   public static readonly DependencyProperty LoadedCommandProperty = DependencyProperty.Register("LoadedCommand", typeof(ICommand), typeof(FrameworkElement), new PropertyMetadata(OnPropertyChanged));
   public static readonly DependencyProperty LoadedCommandExecutorProperty = DependencyProperty.Register("LoadedCommandExecutor", typeof(Action), typeof(FrameworkElement), new PropertyMetadata(OnPropertyChanged));

   private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
      if (!(d is FrameworkElement))
      {
         throw new ArgumentException("Loaded command can only be used on FrameworkElements");
         var executor = GetLoadedCommandExecutor(d);
         if(executor == null)
         {
            executor = () =>
            {
                   var command = GetLoadedCommand(d);
                   command.Execute(e);
         };
            SetLoadedCommandExecutor(d, executor);
            ((FrameworkElement)d).Loaded += (obj, args) => executor();
      }
   }
}
1 голос
/ 23 апреля 2010

Создайте DependencyProperty типа ICommand: -

    #region public ICommand LoadedCommand

    public ICommand LoadedCommand
    {
        get { return GetValue(LoadedCommandProperty) as ICommand; }
        set { SetValue(LoadedCommandProperty, value); }
    }

    public static readonly DependencyProperty LoadedCommandProperty =
            DependencyProperty.Register(
                    "LoadedCommand",
                    typeof(ICommand),
                    typeof(MainPage),
                    new PropertyMetadata(null));

    #endregion public ICommand LoadedCommand

Также добавьте что-нибудь, чтобы действовать как параметр команды: -

    #region public object LoadedCommandParameter

    public object LoadedCommandParameter
    {
        get { return GetValue(LoadedCommandParameterProperty) as object; }
        set { SetValue(LoadedCommandParameterProperty, value); }
    }

    public static readonly DependencyProperty LoadedCommandParameterProperty =
            DependencyProperty.Register(
                    "LoadedCommandParameter",
                    typeof(object),
                    typeof(MainPage),
                    new PropertyMetadata(null));

    #endregion public object LoadedCommandParameter

Теперь настройте его выполнениенапример: -

    public UserControl1()
    {
        InitializeComponent();
        Loaded += UserControl1_Loaded;
    }

    void UserControl1_Loaded(object sender, RoutedEventArgs e)
    {
        if (LoadedCommand != null && LoadedCommand.CanExecute(LoadedCommandParameter))
        {
            LoadedCommand.Execute(LoadedCommandParameter);
        }
    }

Теперь, если ваша ViewModel (имеет команду с именем StartStuff), то: -

  <UserControl1 LoadedCommand="{Binding StartStuff}" .... >
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...