【问题标题】:In uwp when i changes data in c# code it is not updating on front view在 uwp 中,当我在 c# 代码中更改数据时,它不会在前视图上更新
【发布时间】:2019-04-05 09:06:46
【问题描述】:

我正在 uwp 中实现列表视图。我将数据绑定到集合对象的列表视图。当我更改集合中的数据时,它不会更新。Listview 保持原样?请建议我如何更新数据? 提前致谢。

【问题讨论】:

  • 您能否发布一个简单示例,说明您在代码中尝试执行的操作(XAML 视图和与之配套的 C# 代码),以便我可以更好地帮助您?你的问题很模糊,没有例子。
  • 我只使用了 ObservableCollection 而不是列表而不是 INotifyPropertyChanged,这解决了我的问题。

标签: listview uwp-xaml auto-update


【解决方案1】:

当我更改集合中的数据时,它没有更新。Listview 保持原样?

当您的属性值发生变化时,您需要通知绑定客户端。那么,如何通知呢?

您需要为您的自定义类实现INotifyPropertyChanged Interface ,并在属性更改时引发PropertyChanged 事件。

我制作了一个简单的代码示例供您参考:

<Grid>
    <ListView ItemsSource="{Binding tests}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

    <Button Content="update" Click="Button_Click"></Button>
</Grid>
public sealed partial class MainPage : Page
{
    public ObservableCollection<Test> tests { get; set; }
    public MainPage()
    {
        this.InitializeComponent();
        tests = new ObservableCollection<Test>();
        for (int i=0;i<10;i++)
        {
            tests.Add(new Test() { Name="Name "+i});
        }
        this.DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach (var t in tests)
        {
            t.Name = t.Name +" " +DateTime.Now;
        }
    }
}

public class Test:INotifyPropertyChanged
{
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set
        {
            if (_Name != value)
            {
                _Name = value;
                RaisePropertyChanged("Name");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string PropertyName)
    {
        if (PropertyChanged!= null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多