WinUI 3 数据绑定适用于一个对象,但不适用于另一个对象

问题描述 投票:0回答:1

我在 WinUI 数据绑定和 INotifyPropertyChanged 实现方面遇到问题。 我有一个测试类正在按预期工作

public class BasicNotifyChange<T> : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
    public BasicNotifyChange(T value)
    {
        _value = value;
    }
    

    private T _value;
    public T Value
    {
        get => _value;
        set
        {
            if (EqualityComparer<T>.Default.Equals(_value, value)) return;
            
            _value = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
        }
    }
}

另一个类不工作,但正在触发 PropertyChanged 事件

public class InvoiceRowController: Accessible, ICollectionController<BillRowDto>, INotifyPropertyChanged
{
    internal InvoiceRowController(List<Accessible> history) : base(history)
    {}
    
    private string _test;
    public string Test
    {
        get => _test;
        set
        {
            _test = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;
}

我正在这个页面上测试它们

public sealed partial class InvoiceLogPage : Page
{
    private InvoiceRowController RowController { get; set; } = null!;

    private BasicNotifyChange<string> Tester { get; set; } = new("");
    
    public InvoiceLogPage()
    {
        InitializeComponent();
    }

    private async void LoadPage()
    {
        RefreshBar.Visibility = Visibility.Visible;
        
        var list = await RowController.GetItemsAsync();
        Invoices.Clear();
        
        for (var i = 0; i < list.Count; i++)
            Invoices.Add(list[i]);

        RefreshBar.Visibility = Visibility.Collapsed;

        //RowController.Job += "hey";
        Tester.Value += "hey";
        RowController.Test += "hh";
        Sam.Sampl += "aa";
    }

在 xaml 中使用这个

<TextBox Grid.Column="0" Grid.Row="1" Header="Job" Margin="0,5,0,0" Text="{x:Bind RowController.Test, Mode = TwoWay}" />

                <TextBox Grid.Column="1" Grid.Row="1" Header="Invoice" Margin="5,5,0,0" Text="{x:Bind Tester.Value, Mode = TwoWay}" />

Tester.Value 工作完美,但 RowController.Test 的更改未反映在 UI 上

最后一天我一直在搞通用测试(以及其他小测试类),但没有什么能让 InvoiceRowController 工作或小测试不起作用。

c# wpf uwp-xaml inotifypropertychanged winui-3
1个回答
0
投票

正如评论中提到的,

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));

应该是:

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Test)));

但是这里最严重的失败是你没有初始化RowController。所以,

private InvoiceRowController RowController { get; set; } = null!;

应该是这样的:

private InvoiceRowController RowController { get; set; } = new InvoiceRowController(new List<Accessible>());
© www.soinside.com 2019 - 2024. All rights reserved.