Wpf usercontrol with parameterized constructor

We use Microsoft Unity and dependent injection, so we have a parameterized constructor for usercontrol. How to insert this dependency in usercontrol using XAML?

I added usercontrol to XAML as shown below.

xmlns:usrRefundArrivalProcessor="Ttl.Refunds.Wpf.Dashboad.Application.Usercontrols;assembly=Ttl.Refunds.Wpf.Dashboad.Application"
+5
source share
3 answers

Including dependencies does not imply parameterized constructors. In fact, if you look at the samples that come with Unity, most of the dependency injection is done with properties with the [Dependency] attribute.

Unity XAML, . UserControl , [Dependency], XAML.

public class MyUserControl : UserControl
{
  [Dependency]
  public ISomething Something { get; set; }

  [Dependency]
  public IWhatever Whatever { get { return (IWhatever)GetValue(WhateverProperty); } set { SetValue(WhateverProperty, value); }
  public readonly DependencyProperty WhateverProperty = DependencyProperty.Register("Whatever", typeof(IWhatever), typeof(MyUserControl));

  ...
}

, [Dependency] DependencyProperty, CLR, . , .

UnityContainer XAML , "UnityHelper.Container", PropertyChangedCallback BuildUp :

public class UnityHelper
{
  public static IUnityContainer GetContainer(DependencyObject obj) { return (IUnityContainer)obj.GetValue(ContainerProperty); }
  public static void SetContainer(DependencyObject obj, IUnityContainer value) { obj.SetValue(ContainerProperty, value); }
  public static readonly DependencyProperty ContainerProperty = DependencyProperty.RegisterAttached("Container", typeof(IUnityContainer), typeof(UnityHelper), new FrameworkPropertyMetadata
  {
    Inherits = true,
    PropertyChangedCallback = (obj, e) =>
    {
      var container = e.NewValue as IUnityContainer;
      if(container!=null)
      {
        var element = obj as FrameworkElement;
        container.BuildUp(obj.GetType(), obj, element==null ? null : element.Name);
      }
    }
  });
}

UnityContainer , , , :

UnityHelper.SetContainer(this, new UnityContainer() ...);

XAML :

<UserControl ...
  my:UnityHelper.Container="{DynamicResource MainUnityContainer}" />

, , , WPF 98% , Unity . , Unity MVVM. , MVVM , , , , Unity .

+10

. " " UserControl? , , . , , , .

0

, , WPF. Inherits = true , GUI PropertyChangedCallback , , GUI Unity. , , , GUI " " . , UnityInjection .

, UnityInjection codebehind, , MVVM. MVVM, ViewModel , XAML, . ViewModel () Unity, . , .

0

All Articles