我不明白ItemTemplate中的DataTemplate。我有一个为ItemsControl提供ItemsSource的ObservableCollection“StringViewModel”转录。使用StringViewModel填充转录集合正确显示这些字符串。如何绑定ItemsControl中的DataTemplate
在显示每个字符串时,我想让XAML绑定调用MyConverter,以便可以在显示的每个项目上运行附加代码。 (我不是试图改变显示内容,而只是根据显示内容的位置执行一些操作)。
在下面的代码中,MyConverter永远不会被调用。
对ItemsControl中呈现的每个项目调用MyConverter的最佳方式是什么?
任何帮助表示赞赏。
C#
public class StringViewModel : FrameworkElement {...}
private ObservableCollection<StringViewModel> transcription = new ObservableCollection<StringViewModel>();
public ObservableCollection<StringViewModel> Transcription
{
get
{
return transcription;
}
set
{
transcription = value;
}
}
XAML
<ItemsControl
ItemsSource="{Binding Transcription}"
>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas
Background="Transparent"
Width="{x:Static h:Constants.widthCanvas}"
Height="{x:Static h:Constants.heightCanvas}"
/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate> <!-- THIS DOES NOT WORK -->
<ContentControl Content="{Binding Converter={StaticResource MyConverter}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我试图将其更改为:在
<ItemsControl.ItemTemplate>
<DataTemplate>
<StringViewModel ft="{Binding Path=., Converter={StaticResource MyConverter}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
结果:
的ItemTemplate和ItemTemplateSelector的物品被忽略ItemsControl的容器类型已经存在; Type ='StringViewModel'
怎么办?
的StringViewModel被定义为:
public class StringViewModel : FrameworkElement, INotifyPropertyChanged
{
public StringViewModel()
{
}
public StringViewModel(
Point topleft,
string text,
double fontsizediu,
SolidColorBrush brush,
Func<FormattedText,FormattedText> f,
double lineheight)
{
this.text = text;
this.emSize = fontsizediu;
this.color = brush;
this.topleft = topleft;
this.lineheight = lineheight;
this.f = f;
}
protected override void OnRender(DrawingContext dc)
{
ft = new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(new FontFamily("Segoe Script"), FontStyles.Italic, FontWeights.Normal, FontStretches.Normal),
emSize,
color);
ft.TextAlignment = TextAlignment.Left;
// apply special styles
ft = f(ft);
dc.DrawText(ft, topleft);
}
private string text;
private double emSize;
private SolidColorBrush color;
private Func<FormattedText, FormattedText> f;
public Point topleft;
private double? Lineheight;
private FormattedText _ft;
public FormattedText ft
{
get
{
return _ft;
}
set
{
if (_ft != value)
{
_ft = value;
OnPropertyChanged("ft");
}
}
}
哪个结果(效果)你想实现吗?你已经为ItemsControl设置了ItemsSource,但是你没有为Canvas和ContentControl设置一些东西。 – Rang 2014-08-29 02:01:16
@Rang如果没有ItemsControl.ItemTemplate部分,Transcription中的字符串将正确显示在画布上的正确位置。最终,我想使用每个显示项目的位置来执行转换器内的视觉命中测试。转录集合是一个动态变化的FormattedText类型集合。 – 2014-08-29 02:53:59
你的意思是如果你添加''转换器从来没有被调用?并用''出来,它会在Canvas中正确显示'Transcription'?但我写了一个简单的例子,它的工作原理。看到我的临时答案。 –
Rang
2014-08-29 03:13:30