ItemTemplate中的WPF绑定用于自定义ItemControl

时间:2016-02-02 18:12:34

标签: wpf xaml binding datatemplate itemtemplate

我添加了一个WPF自定义控件并使其从ItemsControl派生。该类称为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>

我很确定数据模板中Textbox的绑定不正确,因为我收到以下运行时错误(显示在输出窗口中):

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元素?

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

由于

1 个答案:

答案 0 :(得分:2)

据我所知,它应该只是

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

DataContext,因此ItemTemplate中的所有内容都是P类的实例,所以您需要指定的是Path