Adrian S
Adrian S

Reputation: 544

WPF Binding in ItemTemplate for custom ItemControl

I add a WPF custom control and make it derive from ItemsControl. The class is called IC4 and is declared as follows:

public class IC4 : ItemsControl

I add the following properties to it:

    public class P
    {
        public string S { get; set; }
        public string T { get; set; }
    }

    public List<P> LP { get; set; } = new List<P>();

Then in the constructor I do the following:

    public IC4()
    {
        LP.Add(new P { S = "fred", T = "jim" });
        LP.Add(new P { S = "fred", T = "jim" });
        this.ItemsSource = LP;
        this.DataContext = this;
    }

Visual studio added a style entry to themes/generic.xaml - I have modified it as follows:

<Style TargetType="{x:Type local:IC4}">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <Grid>
                    <!-- this is almost certainly wrong: -->
                    <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=S}"/>
                </Grid>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:IC4}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <ItemsPresenter/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

In mainwindow.xaml I added:

    <StackPanel>
        <Label Content="before"/>
        <local:IC4 ItemsSource="{Binding LP}"/>
        <Label Content="after"/>
    </StackPanel>

I am fairly certain the binding for the Textbox in the data template is incorrect since I get the following runtime error (shown in the output window):

System.Windows.Data Error: 40 : BindingExpression path error: 'S' property not found on 'object' ''ContentPresenter' (Name='')'. BindingExpression:Path=S; DataItem='ContentPresenter' (Name=''); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

How do I set the binding to be able to show the S elements of the LP property?

(Note that for the sake of simplicity I am not interested in property change notifications).

Thanks

Upvotes: 0

Views: 1031

Answers (1)

dkozl
dkozl

Reputation: 33364

As far as I can see it should be just

<DataTemplate>
    <Grid>
        <TextBlock Text="{Binding Path=S}"/>
    </Grid>
</DataTemplate>

DataContext of each item, so for everything in your ItemTemplate, will be an instance of P class so all you should need to specify is the Path

Upvotes: 2

Related Questions