Multibinding WPF

2019-09-17 15:28发布

I am arranging few textblocks in a canvas based on it's locations. sample code snippet is provided below at bottom. For this process I need to access each textblock's Actualwidth and Actual Height inside ItemContainerStyle. I am struggling to access it's properties as below by element name, because it doesn't have a name. How to do it? Do I need to do through templates?

<MultiBinding Converter="{StaticResource BPositionConverter}" ConverterParameter="Left">                            
     <Binding ElementName="TextBlock" Path="ActualHeight" />  <---Problem
     <Binding ElementName="TextBlock"  Path="ActualWidth" />  <---Problem
</MultiBinding>

--Full snippet

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

1条回答
孤傲高冷的网名
2楼-- · 2019-09-17 16:10

Since your data template consist of a single text element you can refer to self to get the actual width and height for the same

so remove the ElementName and apply RelativeSource, should work with this trick

<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>
查看更多
登录 后发表回答