简体   繁体   English

如何从DataTemplate创建实例

[英]How to create an instance from a DataTemplate

I have implemented a custom control that internally uses a ListView within the control template. 我实现了一个自定义控件,该控件在内部使用控件模板内的ListView。 This ListView is accessable by FindParts. 该ListView可通过FindParts访问。 I need to set the ListViews View property to an instance that I have to instanciate programmatically within my custom control. 我需要将ListViews View属性设置为必须在自定义控件中以编程方式实例化的实例。 I want to be able to create this instance from a DataTemplate that can be bound to a property of my custom control. 我希望能够从可以绑定到我的自定义控件的属性的DataTemplate创建此实例。

The problem is that I do not know how to create an instance from a DataTemplate. 问题是我不知道如何从DataTemplate创建实例。

Note that I do not want to bind a GridView directly to the View property (eg from a ResourceDictionary where the DataTemplates x:Shared attribute is set to false) as this leads to problems in the XAML designer (View can't be shared by more than one ListView). 请注意,我不想将GridView直接绑定到View属性(例如,从ResourceTemplatedictionary中,其中DataTemplates x:Shared属性设置为false),因为这会导致XAML设计器出现问题(视图不能由更多用户共享)多于一个ListView)。

Edit: Durig my discussion with grek40 it became clear that it is not possible to provide the GridView within a DataTemplate. 编辑: Durig与grek40的讨论非常清楚,不可能在DataTemplate中提供GridView。 Thus the answer marked as solution does not handle the question how to create an instance from a DataTemplate as implied by the title of my question. 因此,标记为解决方案的答案不能解决问题标题所暗示的问题,即如何从DataTemplate创建实例。

Since you didn't share much code, I made something out of thin air. 由于您没有共享太多代码,因此我凭空做出了一些事情。 The Idea: MyCustomControl is hosting items and for that, a ListView is used in the ControlTemplate . 想法: MyCustomControl托管项目,为此,在ControlTemplate使用ListView A default GridView is included directly in the ControlTemplate but it's possible to change it via MyCustomControl.MyView 默认的GridView直接包含在ControlTemplate但是可以通过MyCustomControl.MyView进行更改

The Custom Control: 自定义控件:

public class MyCustomControl : ItemsControl
{
    static MyCustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
    }


    public ViewBase MyView
    {
        get { return (ViewBase)GetValue(MyViewProperty); }
        set { SetValue(MyViewProperty, value); }
    }

    public static readonly DependencyProperty MyViewProperty =
        DependencyProperty.Register("MyView", typeof(ViewBase), typeof(MyCustomControl), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnMyViewChanged)));

    private static void OnMyViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((MyCustomControl)d).HasCustomView = e.NewValue != null;
    }



    // readonly property to support the Trigger in the ControlTemplate in order to exchange the ListView.View
    public bool HasCustomView
    {
        get { return (bool)GetValue(HasCustomViewProperty); }
        private set { SetValue(HasCustomViewPropertyKey, value); }
    }

    private static readonly DependencyPropertyKey HasCustomViewPropertyKey =
        DependencyProperty.RegisterReadOnly("HasCustomView", typeof(bool), typeof(MyCustomControl), new PropertyMetadata(false));
    public static readonly DependencyProperty HasCustomViewProperty = HasCustomViewPropertyKey.DependencyProperty;
}

The Control Template (note the default GridView and the Trigger for Replacement): 控制模板(请注意默认的GridView和替换触发器):

<Style TargetType="{x:Type local:MyCustomControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <ListView x:Name="PART_ListView"
                              ItemsSource="{Binding Items,RelativeSource={RelativeSource TemplatedParent}}">
                        <ListView.View>
                            <GridView>
                                <GridView.Columns>
                                    <GridViewColumn Header="DEF"/>
                                </GridView.Columns>
                            </GridView>
                        </ListView.View>
                    </ListView>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="HasCustomView" Value="True">
                        <Setter TargetName="PART_ListView" Property="View" Value="{Binding MyView,RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Usage: 用法:

<local:MyCustomControl>
    <!--uses default view-->
    <TextBlock Text="Item 1"/>
    <TextBlock Text="Item 2"/>
</local:MyCustomControl>

<local:MyCustomControl>
    <!--uses custom view-->
    <local:MyCustomControl.MyView>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="ABC"/>
            </GridView.Columns>
        </GridView>
    </local:MyCustomControl.MyView>
    <TextBlock Text="Item 1"/>
    <TextBlock Text="Item 2"/>
</local:MyCustomControl>

Feel free to ask if anything remains unclear. 随时询问是否还有不清楚的地方。 As commented, I don't know how to apply your DataTemplate idea to all this stuff. 如前所述,我不知道如何将您的DataTemplate想法应用于所有这些内容。

Edit: 编辑:

The following is a an example with resource section to define some data and DataTemplate s as well as their possible usage. 以下是带有资源部分的示例,用于定义一些数据和DataTemplate以及它们的可能用法。

<StackPanel>
    <StackPanel.Resources>
        <x:Array x:Key="Items1" Type="{x:Type sys:Int32}">
            <sys:Int32>1</sys:Int32>
            <sys:Int32>2</sys:Int32>
            <sys:Int32>3</sys:Int32>
            <sys:Int32>4</sys:Int32>
        </x:Array>

        <x:Array x:Key="Items2" Type="{x:Type sys:Int32}">
            <sys:Int32>5</sys:Int32>
            <sys:Int32>4</sys:Int32>
            <sys:Int32>6</sys:Int32>
            <sys:Int32>7</sys:Int32>
        </x:Array>

        <CollectionViewSource x:Key="ItemsSource1" Source="{StaticResource Items1}"/>
        <CollectionViewSource x:Key="ItemsSource2" Source="{StaticResource Items2}"/>

        <DataTemplate x:Key="IntegerListTemplate1">
            <local:MyCustomControl ItemsSource="{Binding}">
                <!--uses default view-->
            </local:MyCustomControl>
        </DataTemplate>

        <DataTemplate x:Key="IntegerListTemplate2">
            <local:MyCustomControl ItemsSource="{Binding}">
                <!--uses custom view-->
                <local:MyCustomControl.MyView>
                    <GridView>
                        <GridView.Columns>
                            <GridViewColumn Header="ABC"/>
                        </GridView.Columns>
                    </GridView>
                </local:MyCustomControl.MyView>
            </local:MyCustomControl>
        </DataTemplate>
    </StackPanel.Resources>
    <!--the default view-->
    <ContentControl ContentTemplate="{StaticResource IntegerListTemplate1}" Content="{Binding Source={StaticResource ItemsSource1}}"/>
    <Separator Margin="3"/>
    <!--same items other view-->
    <ContentControl ContentTemplate="{StaticResource IntegerListTemplate2}" Content="{Binding Source={StaticResource ItemsSource1}}"/>
    <Separator Margin="3"/>
    <!--different items same view as second one, no complaints about reusing-->
    <ContentControl ContentTemplate="{StaticResource IntegerListTemplate2}" Content="{Binding Source={StaticResource ItemsSource2}}"/>
</StackPanel>

Edit 2, targeting the commented MCVE: 编辑2,针对评论的MCVE:

I would solve this exactly as I already explained in my first edit. 我将按照我在第一次编辑中已经解释的完全解决这个问题。 Turn your control into a DataTemplate , not the view into a style. 将控件变成DataTemplate ,而不是将视图变成样式。

Replace in MainWindow.xaml: 在MainWindow.xaml中替换:

<!-- old -->
<myctrls:MyControl Grid.Row="0" Grid.Column="0" Style="{StaticResource AddressStyle}" ItemsSource="{Binding Addresses}"/>
<!-- new -->
<ContentControl Grid.Row="0" Grid.Column="0" ContentTemplate="{StaticResource AddressTemplate}" Content="{Binding Addresses}"/>

Same with the other occurences. 与其他事件相同。

In MyControlStyles.xaml (or a renamed file that indicates DataTemplate usage), merge the GridView resource and the Style with the myctrls:MyControl into a DataTemplate . 在MyControlStyles.xaml(或指示DataTemplate使用的重命名文件)中,将GridView资源和Stylemyctrls:MyControl合并到DataTemplate

Old: 旧:

<GridView x:Key="AddressGridView" x:Shared="False">
    <GridViewColumn Header="City" Width="Auto" >
        <GridViewColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding City}" HorizontalAlignment="Left"/>
            </DataTemplate>
        </GridViewColumn.CellTemplate>
    </GridViewColumn>
    <GridViewColumn Header="Country" Width="Auto" >
        <GridViewColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Country}" HorizontalAlignment="Left"/>
            </DataTemplate>
        </GridViewColumn.CellTemplate>
    </GridViewColumn>
</GridView>

<Style x:Key="AddressStyle" TargetType="{x:Type myctrls:MyControl}">
    <Setter Property="SuggestionsView" Value="{DynamicResource AddressGridView}"/>
</Style>

New: 新:

<DataTemplate x:Key="AddressTemplate">
    <!-- the base control -->
    <myctrls:MyControl ItemsSource="{Binding}">
        <!-- this was previously assigned by AddressStyle -->
        <myctrls:MyControl.SuggestionsView>
            <!-- this was previously the AddressGridView -->
            <!-- Same as before, only removed the x:Key and x:Shared -->
            <GridView>
                <GridViewColumn Header="City" Width="Auto" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding City}" HorizontalAlignment="Left"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Country" Width="Auto" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Country}" HorizontalAlignment="Left"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </myctrls:MyControl.SuggestionsView>
    </myctrls:MyControl>
</DataTemplate>

Same procedure for the ProductsStyle . ProductsStyle相同的过程。

If you don't like the ContentControl wire-up approach, consider the creation of additional viewmodels that host then collections, like AddressListViewModel . 如果您不喜欢ContentControl的连接方法,请考虑创建用于承载集合的其他视图模型,例如AddressListViewModel This would allow you to handle the DataTemplate by DataType instead of resource key and explicit usage in ContentControl . 这将允许您通过DataType处理DataTemplate ,而不是ContentControl的资源键和显式用法。

You could implement your own DataTemplateSelector, which then dynamically creates your one-time-use DataTemplate, roughly like that: 您可以实现自己的DataTemplateSelector,然后动态创建您的一次性DataTemplate,大致如下所示:

public DataTemplate GenerateTemplate() {
  var template = new DataTemplate();
  var p = new FrameworkElementFactory(typeof(Grid));
  p.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Left);
  p.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
  ...
  template.VisualTree = p;
  return template;
}

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

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