【问题标题】:x:Bind to ActualWidth does not appear to workx:Bind to ActualWidth 似乎不起作用
【发布时间】:2022-01-26 19:42:18
【问题描述】:

我正在编写 C# UWP。我有一个带有以下示例代码的 UserControl:

<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>

此代码有效。但是,我想使用较新的x:Bind,所以我将{Binding Mode=OneWay, Path=ActualWidth, ElementName=Root} 替换为{x:Bind Mode=OneWay, Path=Root.ActualWidth}。现在由于某种原因,整个 AutoSuggestBox 都从屏幕上消失了,我假设它的宽度是 0。

为什么会发生这种情况,我该如何解决?

【问题讨论】:

  • 这可能是由于 Binding 和 {x:Bind} 之间的差异造成的。 {x:Bind} 执行在编译时生成的专用代码,而 {Binding} 使用通用运行时对象检查。您可能需要在UserControl 中实现INotifyPropertyChanged 接口。

标签: c# xaml uwp winrt-xaml


【解决方案1】:

正如 Roy Li - MSFT 所说,您可能必须在您的课程中实现 INotifyPropertyChanged 接口 (UserControl.xaml.cs)。但在此之前,您需要在该类中添加 2 个新的命名空间。

第一个是System.ComponentModel(用于访问INotifyPropertyChanged) 第二个是System.Runtime.CompilerServices(访问CallerMemberNameAttribute)

所以你的类现在应该是这样的

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;
}

你的 Page.xaml 像这样

<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>

两天前我也遇到了同样的麻烦,所以我希望它会起作用。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 2016-02-01
    • 2020-09-23
    • 2010-12-05
    • 2011-06-14
    • 2015-01-10
    • 2016-02-24
    • 2011-01-18
    相关资源
    最近更新 更多