我有一个网格,其宽度是“1 *”。因此,实际宽度决定在运行时,我认为。内网我有另外一个网格我想设置于母公司电网的运行时宽的宽度。我该怎么办,在XAML通过有约束力的。
这实际上将帮助你我猜
Width="{Binding ActualWidth, ElementName=parentElementName}"
此结合宽度所提供的父元素或元素名称
这是通用的解决方案可以工作无处不在。你不会需要编写父元素名称。这将确定其父亲,并且将采取母公司的宽度。
Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}"
我认为做同样的事情,最简单的方法是:
HorizontalAlignment="Stretch"
即不使用绑定,你已经问过,但它更容易。
如果你在代码背后做,这对我的作品。它具有额外的优势结合不必是大部头的孩子:
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);
}
用法:
child.BindWidth(parent);
Width="{Binding Width, RelativeSource={RelativeSource AncestorType={x:Type Parent}, Mode=FindAncestor}}"
如果两个控制DataContext的是不同的。
如果它是一个模板中使用:
<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>