2014-02-12 216 views
0

我有一個可調整大小的小矩形,我需要顯示從邊框到圖像最近側的像素距離。WPF綁定問題

目前紅色數字是藍色矩形的寬度和高度。因爲紅色數字應該顯示藍色條的長度。

我有以下綁定:

<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

+0

你有什麼'DataContext'得到'Width'和'Height'?你從哪裏得到這些......來自'sizeInfo'' Grid'? – Sankarann

+0

@Sankarann表示網格是樣式的一部分,數據上下文是DataContext =「{Binding RelativeSource = {RelativeSource TemplatedParent}} – Terko

回答

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