我在画布中根据它的位置安排了几个文本块。示例代码段在底部提供。对于此过程,我需要访问ItemContainerStyle中每个文本块的Actualwidth和Actual Height。我正在努力通过元素名称访问它的属性,因为它没有名称。怎么做?我需要通过模板吗?
<MultiBinding Converter="{StaticResource BPositionConverter}" ConverterParameter="Left">
<Binding ElementName="TextBlock" Path="ActualHeight" /> <---Problem
<Binding ElementName="TextBlock" Path="ActualWidth" /> <---Problem
</MultiBinding>
- 完整代码段
<ItemsControl ItemsSource="{Binding Locations}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="Point">
<TextBlock Text="{Binding}" Width="40" Height="20" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left">
<Setter.Value>
<MultiBinding Converter="{StaticResource BPositionConverter}" ConverterParameter="Left">
<Binding ElementName="TextBlock" Path="ActualHeight" /> <---Problem
<Binding ElementName="TextBlock" Path="ActualWidth" /> <---Problem
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
答案 0 :(得分:2)
由于您的数据模板由单个文本元素组成,您可以引用self来获取相同的实际宽度和高度
所以删除ElementName并应用RelativeSource,应该使用这个技巧
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left">
<Setter.Value>
<MultiBinding Converter="{StaticResource BPositionConverter}"
ConverterParameter="Left">
<Binding Path="ActualHeight"
RelativeSource="{RelativeSource Self}" />
<Binding Path="ActualWidth"
RelativeSource="{RelativeSource Self}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>