DataTemplate 中用于自定义 ItemsControl 的 WPF 绑定

WPF Binding in ItemTemplate for custom ItemControl

我添加了一个 WPF 自定义控件并使其派生自 ItemsControl。 class 称为 IC4,声明如下:

public class IC4 : ItemsControl

我给它添加了以下属性:

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

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

然后在构造函数中我执行以下操作:

    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在themes/generic.xaml中添加了一个样式入口——我修改如下:

<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>

在mainwindow.xaml我补充说:

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

我相当确定数据模板中文本框的绑定不正确,因为我收到以下运行时错误(显示在输出 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')

如何设置绑定才能显示 LP 属性 的 S 元素?

(请注意,为了简单起见,我对 属性 更改通知不感兴趣)。

谢谢

据我所知应该只是

<DataTemplate>
    <Grid>
        <TextBlock Text="{Binding Path=S}"/>
    </Grid>
</DataTemplate>
每个项目的

DataContext,因此对于 ItemTemplate 中的所有内容,都将是 P class 的一个实例,因此您需要指定的是 Path