c# - 更新特定的 ListView 项值

标签 c# wpf listview

我有一个像这样的 ListView:

<ListView.View>
  <GridView>
     <GridViewColumn x: Name = "KeyColumn1" Header = "Key" Width = "100" DisplayMemberBinding = "{Binding Path=Label}"/ >
     <GridViewColumn x: Name = "ValueColumn1" Header = "Value" Width = "130" DisplayMemberBinding = "{Binding Path=Value}"/>
  </GridView>
</ListView.View>

时间定义如下:public DateTime time = DateTime.Now;

如何用两种不同的方法更新时间?我能够获取时间并将其显示在 Ringing() 中,但时间未在 Established() 中更新。

private void Ringing()
{
  CallTabLv1.Items.Add(new { Label = "Time", Value = time.ToString() });
  CallTabLv1.Items.Add(new { Label = "Call Type", Value = "Call in" });
}

private void Established()
{
  CallTabLv1.Items.Refresh();
}

我知道最简单的方法是清除项目并在 Established() 中再次添加,但是由于需要添加两个以上的项目,我不希望代码看起来冗长而且重复。我想到的另一种方法是删除特定行然后再次插入,但这种方法不适合,因为我的数据是动态的。

最佳答案

而不是使用匿名类型创建一个类似的类型

    public class LabelValuePair:INotifyPropertyChanged
{
    public bool  RequiresTimeRefresh{get { return !string.IsNullOrEmpty(Label) && Label.ToLower() == "time"; }}

    private string label;

    public string Label
    {
        get { return label;}
        set { label = value; }
    }

    private string value;

    public string Value
    {
        get { return value; }
        set { this.value = value; Notify("Value");}
    }

    public LabelValuePair(string label, string value)
    {
        this.Label = label;
        this.Value = value;
    }

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

    public event PropertyChangedEventHandler PropertyChanged;
}

振铃方式

        private void Ringing(DateTime time)
    {
        CallTabLv1.Items.Add(new LabelValuePair("Time", time.ToString()));
        CallTabLv1.Items.Add(new LabelValuePair("Call Type", "Call in"));
    }

既定方法

        private void Established()
    {
        foreach (LabelValuePair item in CallTabLv1.Items)
        {
            if (item.RequiresTimeRefresh)
                item.Value = DateTime.Now.ToString();
        }
    }

现在您甚至不必调用 Refresh.NotifyPropertyChanged 就可以做到这一点。

关于c# - 更新特定的 ListView 项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31823234/

相关文章:

c# - 未找到 Stripe Webhook Controller

c# - 在一台 Visual Studio 开发服务器中运行多个 Web 应用程序?

c# - 具有空值的 WPF ComboBox SelectedValue 绑定(bind)显示为空白

java - Android Studio 预览版未显示 ListView 示例

java - ListView 消失了

python - 有没有人在 pyqt 5 中实现了一种将所选项目从一个 ListView 框移动到另一个 ListView 框的方法?

c# - .net 正则表达式拆分

c# - 在 C# 中将字符串数组编码为 char **

c# - Windows Phone 8 应用程序动态/以编程方式在 g 网格/面板中创建按钮

c# - WPF ListView 多选 MVVM 带最少的代码