我有一个包含网格的主窗口,在窗口加载事件期间,我将动态创建用户控件的实例并将其添加到网格中。为了让用户控件在调整主窗口大小时自适应,我想将用户控件的宽度和高度绑定到网格的ActualWidth
和ActualHeight
。
第一种方法是在代码中创建绑定对象,在 window_loaded 事件的同一个地方,
Binding widthBinding = new Binding("ActualWidth");
widthBinding.Source = panel;
BindingOperations.SetBinding(uc, WidthProperty, widthBinding);
Binding heightBinding = new Binding("ActualHeight");
heightBinding.Source = panel;
BindingOperations.SetBinding(uc, HeightProperty, heightBinding);
panel.Children.Add(uc);
它按预期工作。
第二种方法是在用户控件的 xaml 文件中使用 xaml 绑定,
<UserControl x:Class="S2T.RAHS2.ContentAcquisition.FileViewer.WordViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="UserControl_Loaded" Unloaded="UserControl_Unloaded"
Width="{Binding ElementName=ContainerElement, Path=ActualWidth}"
Height="{Binding ElementName=ContainerElement, Path=ActualHeight}">
或者
<UserControl x:Class="S2T.RAHS2.ContentAcquisition.FileViewer.WordViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="UserControl_Loaded" Unloaded="UserControl_Unloaded"
Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}, AncestorLevel=1}, Path=ActualWidth}"
Height="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}, AncestorLevel=1}, Path=ActualHeight}">
但这没有用。
我可以知道 xaml 方法有什么问题吗?