gpt4 book ai didi

c# - x :bind UI not update when PropertyChanged in UWP

转载 作者:行者123 更新时间:2023-12-03 10:25:41 24 4
gpt4 key购买 nike

我正在使用 x:BindINotifyPropertyChanged 更新 UWP 应用程序中的 UI。但它的行为类似于 OneTime 绑定(bind),即使我将其设置为 OneWay

Bindings.Update() 有效,但我想知道为什么 INotifyPropertyChanged 失败。

XAML

<TextBlock Text="{x:Bind staffVM.Name, Mode=OneWay}"/>

隐藏代码:

private StaffViewModel staffVM;
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// I want to change staffVM according to ListView's selection.
staffVM = staffListView.SelectedItem as StaffViewModel;
staffVM.Update(); // If change this to Bindings.Update(), It works.
}

View 模型:

public class StaffViewModel: INotifyPropertyChanged
{
private Character character;
public string Name => character.name == string.Empty ? null : character.name;
public void Update()
{
RaisePropertyChanged(string.Empty);
}

public event PropertyChangedEventHandler PropertyChanged;

public void RaisePropertyChanged([CallerMemberName]string propName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}

最佳答案

首先,您需要指定要更新的变量的名称:

public void Update()
{
RaisePropertyChanged(nameof(Name));
}

文档和示例:https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.data.inotifypropertychanged.propertychanged

其次,默认情况下x:Bind是OneTime要修复此问题,请添加 Mode="OneWay"

Mode Specifies the binding mode, as one of these strings: "OneTime", "OneWay", or "TwoWay". The default is "OneTime". Note that this differs from the default for {Binding}, which is "OneWay" in most cases.

请阅读文档 https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension

关于c# - x :bind UI not update when PropertyChanged in UWP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55337531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com