【问题标题】:Dynamic DataTemplate via UserControl with Binding Parameter通过带有绑定参数的 UserControl 的动态 DataTemplate
【发布时间】:2018-01-10 17:57:07
【问题描述】:

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

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

我分享一个代码作为例子。

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

运行时;

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 = this 语句,代码不会出错。但这次绑定在用户控制下不起作用。

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

谢谢...

【问题讨论】:

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


    【解决方案1】:

    我已经解决了。

    我没有使用 this.DataContext = this;在构造函数中。

    这里是xaml代码;

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

    这里是 ucPosListeConteiner C# 代码;

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

    我在 UserControl_Loaded 中将值与 C# 绑定

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

    我可以绑定并获取导入参数。

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 2017-02-18
      • 2016-03-23
      • 2015-11-30
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2018-04-26
      相关资源
      最近更新 更多