我有以下 ProductList 模板片段
<Style x:Key="ProductListStyle" TargetType="{x:Type s:SurfaceListBox }">
<Setter Property="Background" Value="{DynamicResource {x:Static s:SurfaceColors.ListBoxItemBackgroundBrushKey}}" />
<Setter Property="SelectionMode" Value="Single" />
<Setter Property="Height" Value="234" />
<Setter Property="ItemTemplateSelector">
<Setter.Value>
<sc:ProductListTemplateSelector>
<sc:ProductListTemplateSelector.NormalItemTemplate>
<DataTemplate>
<StackPanel RenderTransformOrigin="0.5, 0.5"
Margin="7,0,0,0"
MinWidth="171" MaxWidth="171"
MinHeight="235" MaxHeight="235">
<Image Margin="14,21,21,11" Source="{Binding XPath=@Image}"
Height="149" Width="101" />
<TextBlock Text="{Binding XPath=@Name}"
MaxWidth="116"
FontSize="12"
Margin="21,0,21,21"
FontFamily="Segoe360"
TextAlignment="Center"
TextWrapping="Wrap"
Foreground="{DynamicResource {x:Static s:SurfaceColors.ListBoxItemForegroundBrushKey}}"
HorizontalAlignment="Center" />
</StackPanel>
</DataTemplate>
</sc:ProductListTemplateSelector.NormalItemTemplate>
我需要使用我的用户控件替换要设置的这种样式的 DataTemplate,例如
<local:MyUserControl>
通过仅在部分之间保留,当我的 Itemsource 设置为 myUserControl 的集合时,我没有显示控件
最佳答案
通常我只是将 DataTemplate 添加到 Resources
中。这可以是 <Window.Resources>
或<App.Resources>
如果数据模板是全局的,或 FrameworkElement.Resources
如果模板只能在指定范围内应用。例如,将模板添加到 ListView.Resources
只会在特定的 ListView 中应用模板。
<Window.Resources>
<DataTemplate DataType="{x:Type local:ProductModel}">
<local:MyUserControl />
</DataTemplate>
</Window.Resources>
作为旁注,您最初的问题让我相信您将 ListView 绑定(bind)到 MyUserControl
的集合对象。我真的不推荐这样做,但如果是这种情况,您可以使用 ContentControl
在你的 DataTemplate 中,它是 Content
绑定(bind)到您的对象,它应该正确显示。
<ContentControl Content="{Binding }" />
关于wpf - 将用户控件设置为数据模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8298362/