-1

我正在尝试Textblock通过编译绑定使两种方式绑定工作x:Bind

问题: 即使设置了双向绑定模式和 PropertyChanged 源触发器。无法让它工作。当对象属性 balance 在其后面的代码中更改时,它不会在 UI 中更新。

下面是代码。

XAML

<TextBlock  x:Name="Balance"
            Text="{x:Bind classObject.Balance,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

代码隐藏

private ClassName classObject = new ClassName() { Name = "Foo",Balance = 100 };
public Observable ViewModel { get; } = new Observable();
private void NavLinksList_ItemClick(object sender,ItemClickEventArgs e)
{
    classObject = new ClassName() { Name = "Blah",Balance = 10 * new Random().NextDouble() * (50 - 1) + 1 };
}

可观察的

public class Observable : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return;
        }

        storage = value;
        OnPropertyChanged(propertyName);
    }

    protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

替代解决方案

手动设置Textblock.Text后面的代码。

但问题是属性更改事件应该可以工作并自动更新文本块而无需显式编码。

我搜索了其他问题,但找不到类似的问题。

4

1 回答 1

1

如果要更新 的数据绑定Text属性,TextBlock则应设置它绑定到的源属性,即 的Balance属性classObject。另请注意,ClassName该类应实现INotifyPropertyChanged接口并引发更改通知。

classObject字段设置为 a 的新实例ClassName不应该更新TextBlock,除非您Bindings.Update()之后调用。

于 2018-07-18T14:07:31.167 回答