【发布时间】:2016-05-11 16:39:49
【问题描述】:
我添加了一个 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>
我相当肯定数据模板中文本框的绑定不正确,因为我收到以下运行时错误(显示在输出窗口中):
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 元素?
(请注意,为了简单起见,我对属性更改通知不感兴趣)。
谢谢
【问题讨论】:
-
除了 dkozl said 之外,您还在构造函数中对 DataContext 进行了硬编码,这意味着您尝试传递给它的任何内容,例如
ItemsSource="{Binding LP}",都不会按预期工作。你不应该像这样在任何 UserControl 中硬编码你的 DataContext,因为它会阻止任何其他数据与该 UserControl 一起使用。
标签: wpf xaml binding datatemplate itemtemplate