wpf - 将用户控件设置为数据模板

标签 wpf xaml binding

我有以下 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/

相关文章:

java - Spring-Boot - 只有对象的某些变量是绑定(bind)的

c# - 未在任务栏中显示的 WPF ToolWindow 阻止应用程序

wpf - 在代码中添加项目时将 ItemTemplate 用于 TreeView

c# - 如何使用 OnPlatform Xamarin 更改 BackgroundColor

C# WPF 组合框选择第一项

c# - XPath 绑定(bind)以读取 wpf 中的 InnerXml

java - 如何将一种语言(例如 python)绑定(bind)到另一种语言(例如 C++)?

wpf - 允许 TextBox 调整大小,但不会随着用户输入而增长

wpf - TemplatePart发现

wpf - WPF 必应 map 中的信息框