how to bind width of child element to width of parent element in silverlight

眉间皱痕 提交于 2019-12-02 16:58:29

This will actually help you I guess

Width="{Binding ActualWidth, ElementName=parentElementName}"

This binds the width to the parent element or the element name provided

This is generic solution which may work everywhere. You wouldn't need to write parent element name. This will identify its parent and will take parent's width.

Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}"

I think that easiest way to do same thing is:

HorizontalAlignment="Stretch"

That is not using binding as you have been asked, but it is easier.

If you are doing it in CodeBehind, this works for me. It has the added advantage that bindMe does not have to be a child of toMe:

public static void BindWidth(this FrameworkElement bindMe, FrameworkElement toMe)
{
  Binding b = new Binding();
  b.Mode = BindingMode.OneWay;
  b.Source = toMe.ActualWidth;
  bindMe.SetBinding(FrameworkElement.WidthProperty, b);
}

usage:

child.BindWidth(parent);
Gaurav Panwar
 Width="{Binding Width, RelativeSource={RelativeSource AncestorType={x:Type Parent}, Mode=FindAncestor}}"

if both controls DataContext is different.

If it is inside a Template use this:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical">
                <Image Width="{TemplateBinding Width}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Source="TestImage.png"/>
                <TextBlock HorizontalAlignment="Center" Text="Test Text"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!