binding declared in xaml does not work

1k views Asked by At

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?

1

There are 1 answers

1
Andrew Keith On

Can you try using the alignments instead of binding?

<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" 
        HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>

The problem with binding is that the ActualHeight and ActualWidth might increase if something in the panel makes it increase. This is especially true with StackPanels.

If you arr using a Grid, it might work with binding to the parent ActualWidth and ActualHeight. I have found that sometimes it works, but often something in the panel makes the size increase and messes up the binding.