我的 UserControl 的 TextBlock 绑定一次都没有更新

My UserControl's TextBlock binding doesn't update even once

我知道这个问题已经被问过很多次了。我读了很多,尝试了不同的方法,但仍然无法正常工作。

xaml 代码是一个用户控件:

<Grid Name="middle">
    <d:TextBlock Text="{x:Bind LayerNodeData.CleanName, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Foreground="WhiteSmoke" FontSize="12" FontFamily="Arial" VerticalAlignment="Center" RelativePanel.RightOf="visibleUI" DoubleTapped="OnEditNameBegin" />
</Grid>

我将 this.DataContext 和 Grid 的 DataContext 都设置为数据实例。

c#

public ucLayerRow(ImageLayerNode data)
{
        LayerNodeData = data;

        DataContext = LayerNodeData;

        this.InitializeComponent();

        middle.DataContext = LayerNodeData;

        LayerNodeData.NotifyPropertyChanged("CleanName"); // test if it work

        RefreshUI();
}

型号class

public partial class ImageLayerNode : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            // PropertyChanged is always null.
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
        
    public string mCleanName = string.Empty;
    public string CleanName { 
        get => mCleanName;
        set { mCleanName = value; NotifyPropertyChanged();}
    }
    ....
}

我尝试向 PropertyChanged 添加断点,发现它始终为 null,因此永远不会被调用。我也试过将模式更改为 OneWay、TwoWays,但仍然没有。

文本块是空的,甚至一次都没有得到值。

用户控件就这样添加到主页了。不确定是否相关。

var rowUI = new ucLayerRow(layerNode);                        
layerContainer.Children.Add(rowUI);

My UserControl's TextBlock binding doesn't update even once

在测试过程中,问题看起来是您使用 design time 作为用户控件。 <d:TextBlock/> 请删除 d: 并使您的用户控件如下所示。

Xaml

<Grid>
    <TextBlock
        VerticalAlignment="Center"
        FontFamily="Arial"
        FontSize="12"
        Foreground="Red"
        Text="{x:Bind LayerNodeData.CleanName, Mode=OneWay}" />
</Grid>

代码隐藏

public sealed partial class ucLayerRow : UserControl
{
    public ucLayerRow(ImageLayerNode data)
    {
        this.InitializeComponent();
        LayerNodeData = data;
    }
 
    public ImageLayerNode LayerNodeData { get; set; }
}
public partial class ImageLayerNode : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            // PropertyChanged is always null.
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private string mCleanName = string.Empty;
    public string CleanName
    {
        get => mCleanName;
        set { mCleanName = value; NotifyPropertyChanged(); }
    }

}