ContentPresenter in ItemControl.ItemTemplate for displaymemberpath of control items

I want to know, one way or another, to put a contentpresenter in the itemtemplate of the control to display my data. I don't need hard-coded code binding like Text = "{Binding username}" because I am creating a custom control, I think the ContentPresenter is what I want. But after I tried using contentpresenter it gave me a stackoverflowexception.

    <ItemsControl ItemsSource="{Binding SelectedItems, ElementName=listbox}" DisplayMemberPath={Binding DisplayMemberPath}">
        <ItemsControl.ItemPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock x:Name="Separator" Text=", "/>
                    <ContentPresenter/>
                    <!--<TextBlock Text="{Binding username}"/>-->
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

      

That's my code. If without these seperator and itemtemplate, I can display my data just using displaymemberpath, but it adds all the name together. I still find any solution to resolve it. Hopefully you can provide some ideas for this.

+3


source to share


2 answers


I found an easier way to solve this problem using a horizontal list. thanks for answers



0


source


The answer is no, you cannot. A is ContentPresenter

supposed to be used in ControlTemplate

, not in DataTemplate

, so it is not a valid control. From the linked page on MSDN:

You usually use ContentPresenter

in ControlTemplate

for ContentControl

to indicate where the content should be added.



What you can do alternatively is declare the number DataTemplate

in the section Resources

(bundled with Binding Path

s) for different datatypes and omit directives x:Key

eg. don't name them. Also, don't list one for ItemsControl.ItemTemplate

.

With this, WPF implicitly chooses the correct one DataTemplate

for the respective data type and therefore you can have different outputs for different data types. See the "DataType Property" section of the MSDN Data Overview page for a further explanation of this technique.

+2


source







All Articles