动态DataTemplate通过UserControl与绑定参数

时间:2017-08-03 08:34:37

标签: c# dynamic data-binding user-controls datatemplate

我需要在ListView中动态使用DataTemplate。此datatemplate是用户控件。我可以动态调用用户控件。但是我无法从用户控件中读取项目。

    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);}
    }

我将一个代码作为一个例子。

 viewModelUcPosListeConteiner model;

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

和构造函数;

{{1}}

运行;

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)

如果我在构造函数中删除this.DataContext =此语句,代码不会给出错误。但这次绑定不能在用户控制中工作。

如何在UserControl中获取传出数据和绑定?

谢谢...

1 个答案:

答案 0 :(得分:0)

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.