I have a main window which contains a grid, during the window loaded event, I will dynamically create an instance of a user control and add it to grid. In order to let the user control to adapt itself when the main window is resized, I want to bind the user control's width and height to the grid's ActualWidth and ActualHeight.
The first way is to create the binding object in code,same place in the window_loaded event,
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);
it worked as expected.
The second way is to use xaml binding in the user control's xaml file,
<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}">
or
<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}">
But this did not work.
May I know what is wrong with the xaml approach?