多重绑定 WPF [英] Multibinding WPF

查看:35
本文介绍了多重绑定 WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据位置在画布中排列几个文本块.下面提供了示例代码片段.对于这个过程,我需要在 ItemContainerStyle 中访问每个文本块的实际宽度和实际高度.我正在努力按元素名称访问它的属性,如下所示,因为它没有名称.怎么做?我需要通过模板来做吗?

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>

--完整代码段

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

推荐答案

由于您的数据模板由单个文本元素组成,因此您可以引用 self 以获得相同的实际宽度和高度

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

所以删除ElementName并应用RelativeSource,应该可以使用这个技巧

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>

这篇关于多重绑定 WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆