WPF绑定麻烦

时间:2014-02-12 12:53:09

标签: c# wpf xaml binding

我有一个可调整大小的矩形,我需要显示从边框到图像最近边的像素距离。

目前红色数字是蓝色矩形的宽度和高度。结果红色数字应该显示蓝色条的长度。

我有以下绑定:

<Grid x:Name="sizeInfo" SnapsToDevicePixels="True">
  <TextBlock Text="{Binding Width, StringFormat={}{0:0}}" Background="Transparent" Padding="0,0,0,0" Foreground="#FF0000" Margin="0,0,0,-21" HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
  <TextBlock Text="{Binding Width, StringFormat={}{0:0}}" Background="Transparent" Padding="0,0,0,0" Foreground="#FF0000" Margin="0,-21,0,0" HorizontalAlignment="Center" VerticalAlignment="Top"/>

  <TextBlock Text="{Binding Height, StringFormat={}{0:0}}" Background="Transparent" Foreground="#FF0000" Padding="0,0,0,0" Margin="-21,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center"/>
  <TextBlock Text="{Binding Height, StringFormat={}{0:0}}" Background="Transparent" Foreground="#FF0000" Padding="0,0,0,0" Margin="0,0,-21,0" HorizontalAlignment="Right" VerticalAlignment="Center"/>
</Grid>     

问题在于我无法弄清楚绑定应该是什么样子。可能有做这类事情的常用方法,但我不知道。

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个:

<Rectangle Name="MyRect"
           Fill="Gainsboro"
           Width="174"
           Height="80" />

<Grid Name="SizeInfo"
      Width="{Binding Path=Width, ElementName=MyRect}" 
      Height="{Binding Path=Height, ElementName=MyRect}"
      HorizontalAlignment="Center" 
      VerticalAlignment="Center">

    <!-- StringFormat in this case is not required -->
    <TextBlock Text="{Binding Path=Width, ElementName=MyRect}" ... />
    <TextBlock Text="{Binding Path=Width, ElementName=MyRect}" ... />

    <TextBlock Text="{Binding Path=Height, ElementName=MyRect}" ... />
    <TextBlock Text="{Binding Path=Height, ElementName=MyRect}" ... />
</Grid>

<强> Output

enter image description here