更新相关属性一次而不是两次 [英] Updating dependent property once instead of twice

查看:147
本文介绍了更新相关属性一次而不是两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ViewModel中,我有两个属性类型的日期时间。他们被绑定在XAML与TwoWay模式。当我更新它们时 - OnPropertyChanged引发在第三个属性的这个Datetime属性的一部分。所以我想同时更新两个Datetime属性一次更新第三个属性,而不是更新第三个属性两次。怎么可以??
代码应用:

In my ViewModel I have two properties type of Datetime. They are bound in XAML with TwoWay mode. When I update each of them - OnPropertyChanged raises in set part of this Datetime property for the third property. So I want to update the third property only once when I update two Datetime properties at the same time, instead of updating third property twice. How it can be archieved? Code applied:

//1
public DateTime StartDate
{
    ...
    set
    {
        this.selectedEndDate = value;
        this.OnPropertyChanged("StartDate");
        this.OnPropertyChanged("MyList");
    }
}
//2
public DateTime EndDate
{
    ...
    set
    {
        this.selectedEndDate = value;
        this.OnPropertyChanged("EndDate");
        this.OnPropertyChanged("MyList");
    }
}
//third property
public IEnumerable<MyObject> MyList
{
    get
    {
        return _data.Where(kvp=> kvp.Key.Date >= Start && kvp.Value.Date <= End).Select(kvp => kvp.Value);
    }
}


推荐答案

你可以通过在其中一个日期属性更改时启动的计时器来延迟 MyList 属性更改通知。这不仅可以避免在两个属性同时更改时发出双重通知,而且还可以防止其中一个属性变化太频繁时频繁发送通知。

You may delay the MyList property change notification by means of a timer that is started whenever one of the date properties changes. This would not only avoid double notifications when both properties change "at the same time", but would also protect against frequent notifications when one of the properties changes too frequently.

通过停止并重新启动每个属性更改,定时器将被重置,因此您可以在实际通知 MyList 属性更改之前,随后进行许多更改。

The timer would be reset on every property change by stopping and restarting it, hence you can have many subsequent property changes before actually notifying the MyList property change.

下面的代码示例使用 DispatcherTimer 执行此任务。当然,你必须为 Interval 的价值找到合理的价值。

The code example below uses a DispatcherTimer to perform this task. Of course you have to find a sensible value for the Interval value.

private DispatcherTimer notifyTimer;

public ViewModel()
{
    notifyTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) };
    notifyTimer.Tick += OnNotifyTimerTick;
}

private void OnNotifyTimerTick(object sender, EventArgs e)
{
    OnPropertyChanged("MyList");
    notifyTimer.Stop();
}

public DateTime StartDate
{
    ...
    set
    {
        selectedEndDate = value;
        OnPropertyChanged("StartDate");
        notifyTimer.Stop();
        notifyTimer.Start();
    }
}

public DateTime EndDate
{
    ...
    set
    {
        selectedEndDate = value;
        OnPropertyChanged("EndDate");
        notifyTimer.Stop();
        notifyTimer.Start();
    }
}

这篇关于更新相关属性一次而不是两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆