wpf 如何在silverlight中将子元素的宽度绑定到父元素的宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18864831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to bind width of child element to width of parent element in silverlight
提问by ch.smrutiranjan parida
I have a grid whose width is "1*". So the actual width decided at runtime I think. Within that grid I have another grid whose width I want to set to the runtime width of parent grid. How Can I do that in xaml through binding.
我有一个宽度为“1*”的网格。所以我认为实际宽度是在运行时决定的。在该网格中,我有另一个网格,我想将其宽度设置为父网格的运行时宽度。我如何通过绑定在 xaml 中做到这一点。
回答by Anobik
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
这将宽度绑定到父元素或提供的元素名称
回答by Rudresh Bhatt
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}"
回答by RockLegend
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.
这不是按照您的要求使用绑定,但它更容易。
回答by Gaurav Panwar
Width="{Binding Width, RelativeSource={RelativeSource AncestorType={x:Type Parent}, Mode=FindAncestor}}"
if both controls DataContext is different.
如果两个控件 DataContext 不同。
回答by William Jockusch
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:
如果您在 CodeBehind 中执行此操作,这对我有用。它还有一个额外的优势,即 bindMe 不必是 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);
回答by AhmadReza Saghari
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>