Home > Back-end >  x:Bind to ActualWidth does not appear to work
x:Bind to ActualWidth does not appear to work

Time:01-18

I'm programming C# UWP. I have a UserControl with the following sample code:

<UserControl
    x:Class="Sample.AllocPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="Sample"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Name="Root"
    mc:Ignorable="d">
    <RelativePanel>
        <AutoSuggestBox
            Width="{Binding Mode=OneWay, Path=ActualWidth, ElementName=Root}"
            Margin="50,0,50,0"
            RelativePanel.AlignHorizontalCenterWithPanel="True"
            RelativePanel.AlignVerticalCenterWithPanel="True" />
    </RelativePanel>
</UserControl>

This code works. However, I want to use the newer x:Bind, so I replaced the {Binding Mode=OneWay, Path=ActualWidth, ElementName=Root} with {x:Bind Mode=OneWay, Path=Root.ActualWidth}. For some reason now, the entire AutoSuggestBox is gone from the screen, I'm assuming the width it is getting is 0.

Why does this happen, and how can I fix it?

CodePudding user response:

As Roy Li - MSFT said you probably must implement INotifyPropertyChanged interface in your class (UserControl.xaml.cs). But before you do it you need to add 2 new namespaces into that class.

The first one is System.ComponentModel (to gain access to INotifyPropertyChanged ) And the second one is System.Runtime.CompilerServices (to gain access to CallerMemberNameAttribute)

So your class should now look like this

public sealed partial class MyUserControl1 : UserControl,INotifyPropertyChanged 
{
    public MyUserControl1()
    {
        this.InitializeComponent();
    }                                                                                    
    //some your code

    public double _width;
    public double width
    {
        get
        {
            _width = ActualWidth;
            return _width;
            OnPropertyChanged();
        }
        set
        {                
            _width = value;
            OnPropertyChanged();
        }
    }

    public void OnPropertyChanged([CallerMemberName] string name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

And your Page.xaml like this

<Grid>
    <RelativePanel>
        <AutoSuggestBox
        x:Name="AutoSuggestBox"
        Width="{x:Bind width, Mode=OneWay}"
        Margin="50,0,50,0"
        RelativePanel.AlignHorizontalCenterWithPanel="True"
        RelativePanel.AlignVerticalCenterWithPanel="True" />
    </RelativePanel>
</Grid>

I had kinda same trouble 2 days ago so I hope it will work. :)

  •  Tags:  
  • Related