Search code examples
c#dynamicdata-bindinguser-controlsdatatemplate

Dynamic DataTemplate via UserControl with Binding Parameter


I need to use DataTemplate dynamically in a ListView. This datatemplate is an user control. I can call the user control dynamically. But I can not read item from user control.

         <ListView.ItemTemplate>
            <DataTemplate xmlns:local ="using:App4.Components" x:DataType="models:modelAuftrag">
               <local:ucPosListeConteiner Test="{x:Bind auftragNummer}"/>
            </DataTemplate>
        </ListView.ItemTemplate>

I share a code aside as an example.

    public static readonly DependencyProperty TestProperty = DependencyProperty.Register
       (
            "Test",
            typeof(string),
            typeof(ucPosListeConteiner),
            new PropertyMetadata("")
       );


    public string Test
    {
        get { return (string)GetValue(TestProperty); }
        set { SetValue(TestProperty, value);}
    }

And constructor;

 viewModelUcPosListeConteiner model;

    public ucPosListeConteiner()
    {
        this.InitializeComponent();
        model = new viewModelUcPosListeConteiner();
        this.DataContext = this;
    }

Runtime;

System.InvalidCastException: Unable to cast object of type 'App4.Components.ucPosListeConteiner' to type 'App4.Models.modelAuftrag'. at App4.Components.ucPosListeNew.GetBindingConnector(Int32 connectionId, Object target)

If i remove in constructor this.DataContext = this statement, code give not an error. But this time the binding not working in user control.

How do i get outgoing data and binding in UserControl?

Thank you...


Solution

  • I have solved.

    I didn't use this.DataContext = this; in Constructor.

    Here is xaml code;

      <DataTemplate  x:Key="dt3"  x:DataType="models:modelAuftrag">
            <local:ucPosListeConteiner Test="{x:Bind model}"></local:ucPosListeConteiner>
      </DataTemplate>
    

    Here is ucPosListeConteiner C# code;

        public viewModelUcPosListeConteiner Test
        {
            get { return (viewModelUcPosListeConteiner)GetValue(TestProperty); }
            set { SetValue(TestProperty, value); model = new modelPosListe(); model = value; }
        }
    

    And i binding the Value with C# in UserControl_Loaded

        Binding myBinding = new Binding();
    
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            myBinding.Source = model;
            myBinding.Path = new PropertyPath("test");
            myBinding.Mode = BindingMode.TwoWay;
            myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(txtDeneme, TextBlock.TextProperty, myBinding);
        }
    

    Than i can Binding and get import parameter.