动态加载WPF UserControl

时间:2013-07-15 19:49:28

标签: wpf vb.net dynamic-usercontrols

我有一个抽象基类aComponent和子类CriteriaListQuestion等。

对于每个子类,我有两个对应的UserControl,其名称类似于ueCriteriaListubCriteriaListueQuestionubQuestion等。({ {1}}代表“ue带输入元素”,UserControl代表“ub带按钮”。)

UserControl是“ControllerClass”,其中包含DataContext的属性作为实际my_aComponent实例的getter。当aComponent实例更改时(例如更改为aComponent的实例),我想加载相应的UserControls(在本例中为ueCriteriaList和ubCriteriaList)。

我有两个转换器CriteriaListueControlConverter,它们取类名(例如ubControlConverter)并返回CriteriaList个实例(在这种情况下,UserControl )。

ueCriteriaList

在XAML中,我有两个Public Class ueControlConverter Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert Dim aComp As aComponent = value Dim assemblyKlassenname As String = aComp.GetType.ToString Dim assemblyName As String = Left(assemblyKlassenname, assemblyKlassenname.IndexOf(".") + 1) Dim klassenName As String = Right(assemblyKlassenname, assemblyKlassenname.IndexOf(".") - 1) Dim t As Type = Type.GetType(assemblyName & "ue" & klassenName) Dim o As UserControl = Activator.CreateInstance(t) o.DataContext = value Return o End Function Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack Return value End Function End Class 绑定ContentControlContent="{Binding Path=my_aComponent, Converter={StaticResource _ueControlConverter}。显示了正确的Content="{Binding Path=my_aComponent, Converter={StaticResource _ubControlConverter},但没有绑定到UserControl

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您还需要通过绑定 ContentControl 对象来提供 DataContext 属性。