JHyrdvi
JHyrdvi

Reputation: 23

How to display the Canvas.Left I Canvas.Top property in the content button?

Instead of this text should display properties Canvas.Top and Canvas.Left in Content where the button is located.

<Canvas Background="Lavender">
     <Button Background="AliceBlue"
           Content="Top 20 Left 40"
           Canvas.Top="20"
           Canvas.Left="40" />
</Canvas>

Upvotes: 1

Views: 661

Answers (2)

venkatesan r
venkatesan r

Reputation: 259

No need of converters, simply do it with multibinding,

<Canvas Background="Lavender">
            <Button
                Canvas.Left="40"
                Canvas.Top="20"
                Width="100"
                Height="20"
                Background="AliceBlue">
                <Button.Content>
                    <TextBlock DataContext="{Binding RelativeSource={RelativeSource AncestorType=Button}}">
                        <TextBlock.Text>
                            <MultiBinding StringFormat="{}Top {0} Left {1}">
                                <Binding Path="(Canvas.Top)" />
                                <Binding Path="(Canvas.Left)" />
                            </MultiBinding>
                        </TextBlock.Text>
                    </TextBlock>
                </Button.Content>
            </Button>
        </Canvas>

Upvotes: 0

Peter Duniho
Peter Duniho

Reputation: 70671

There are at least two obvious and straightforward ways to do this:

Create the content inline with TextBlock:

<Button Background="AliceBlue"
        Canvas.Top="20"
        Canvas.Left="40">
  <Button.Content>
    <TextBlock DataContext="{Binding RelativeSource={RelativeSource AncestorType=Button}}">
      <Run Text="Top"/>
      <Run Text="{Binding (Canvas.Top)}"/>
      <Run Text="Left"/>
      <Run Text="{Binding (Canvas.Left)}"/>
    </TextBlock>
  </Button.Content>
</Button>

Use a converter:

class CanvasTopLeftConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (value is UIElement element) ?
            $"Top {Canvas.GetTop(element)} Left {Canvas.GetLeft(element)}" : Binding.DoNothing;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
<Button Background="AliceBlue"
        Content="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource canvasTopLeftConverter}}"
        Canvas.Top="20"
        Canvas.Left="40">
</Button>

Note that when binding to an attached property as the source, you need to put parentheses around the path expression, otherwise WPF will only look on the data context object itself for the name in the path.

Upvotes: 1

Related Questions