C# 代码隐藏中用于动态添加到StackPanel的控件模板
我在my/Themes/Generic.xaml中有以下ControlTemplate:C# 代码隐藏中用于动态添加到StackPanel的控件模板,c#,wpf,xaml,C#,Wpf,Xaml,我在my/Themes/Generic.xaml中有以下ControlTemplate: <ControlTemplate x:Key="GroupList" TargetType="{x:Type Expander}"> <Expander IsExpanded="True"> <Expander.Header> <Label Style="{DynamicResource hea
<ControlTemplate x:Key="GroupList" TargetType="{x:Type Expander}">
<Expander IsExpanded="True">
<Expander.Header>
<Label Style="{DynamicResource headline3}" FontWeight="Light" BorderThickness="0 0 0 1">TEst group</Label>
</Expander.Header>
<ListBox x:Name="lstBoxContacts" Height="auto" BorderThickness="0" VerticalAlignment="Top" AllowDrop="True" PreviewDragOver="lstBoxContacts_PreviewDragOver" Drop="lstBoxContacts_Drop" ItemsSource="{Binding Contacts}">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Fullname}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ContextMenu>
<ContextMenu >
<MenuItem Header="Send Message" Command="local:CustomCommands.cmdMessageWrite"/>
<MenuItem Header="Show Details" Command="local:CustomCommands.cmdContactDetails"/>
<MenuItem Header="Delete" Command="local:CustomCommands.cmdContactDelete"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
</Expander>
</ControlTemplate>
它无法将泛型()转换为FrameworkElement。我是不是没抓住要点 方法可帮助您在模板内查找元素,前提是该模板应用于模板化父级。在您的情况下,您最好使用该方法,创建新的扩展器,使用
Expander.template
属性应用模板,然后将此扩展器添加到StackPanel。子对象集合您不想将自定义控件添加到StackPanel
而不是控制模板
(关于自定义控件)@SWilko我不太擅长WPF,我不确定我是否完全理解所述操作的后果。我认为最简单的解决方案是有一个控件模板,我可以向其中添加数据,然后将整个内容添加到StackPanel。在“new Generic()'是否声明了ResourceDictionary/Themes/Generic.xaml?
Expander grp = (Expander)Template.FindName("GroupList", new Generic());
stkpContactsAndGroups.Children.Add(grp);