简体   繁体   English

如何在WPF中创建带参数的模板?

[英]How to create a template with parameters in WPF?

I have 3 List views.我有 3 个列表视图。 They are very similar.它们非常相似。 The only difference is that their ItemsSource binds to different variables.唯一的区别是它们的 ItemsSource 绑定到不同的变量。 Is there a way to create a template list view with unknown ItemsSource, and I can pass a parameter to fill that ItemsSource?有没有办法创建一个带有未知 ItemsSource 的模板列表视图,我可以传递一个参数来填充那个 ItemsSource?

My code is something like this:我的代码是这样的:

<ListView Name="View1" ItemsSource={"Binding Student1"}>
    <TextBlock Text={"Binding Name"}/>
</ListView>

<ListView Name="View2" ItemsSource={"Binding Student2"}>
    <TextBlock Text={"Binding Name"}/>
</ListView>

<ListView Name="View3" ItemsSource={"Binding Student3"}>
    <TextBlock Text={"Binding Name"}/>
</ListView>

Edit: I might have expressed my question in a wrong way.编辑:我可能以错误的方式表达了我的问题。 I would like to have a separate user control view called "StudentView":我想要一个名为“StudentView”的单独用户控件视图:

<ListView ItemsSource=Parameter1>
    <TextBlock Text={"Binding Name"}/>
</ListView>

So that in my main window, I can do something like this:所以在我的主 window 中,我可以这样做:

<local:StudentView Parameter1={"Binding Student1"}/>

You are on the right track with thinking about templating您在考虑模板方面走在正确的轨道上

What you are looking for is something called a ControlTemplate.您正在寻找的是一种叫做 ControlTemplate 的东西。

Your ControlTemplate would then target the ListView control and use the key word TemplateBinding to pass through the ItemsSource binding from your ListView然后,您的ControlTemplate将以 ListView 控件为目标,并使用关键字TemplateBinding从您的 ListView 传递 ItemsSource 绑定

You would look to add this as a window resource as shown below.您会希望将其添加为 window 资源,如下所示。

<Window.Resources>
    <ControlTemplate x:Key="ListViewTemplate" TargetType="ListView">
        <ListView ItemsSource="{TemplateBinding ItemsSource}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ControlTemplate>
</Window.Resources>

This would enable you to use this template on your ListView controls as shown below这将使您能够在ListView控件上使用此模板,如下所示

<ListView Template="{StaticResource ListViewTemplate}" ItemsSource="{Binding PersonList}"/>
<ListView Template="{StaticResource ListViewTemplate}" ItemsSource="{Binding PersonList1}"/>
<ListView Template="{StaticResource ListViewTemplate}" ItemsSource="{Binding PersonList2}"/>

Hope this gives you what you were looking for希望这能给你你想要的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM