【问题标题】:Set WPF Usercontrol properties before binding在绑定之前设置 WPF 用户控件属性
【发布时间】:2012-12-31 03:18:54
【问题描述】:

我正在制作一个日历用户控件。它有一个开始日期和一个结束日期,就像这样的属性

public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }

这样我就可以像这样调用用户控件

<Local:CalendarControl StartDate="7/1/2013" EndDate="8/11/2013">
</Local:CalendarControl>

现在在用户控件中,我需要计算开始日期和结束日期之间的周数和日期。为此,我自然需要使用选定的开始日期和结束日期。但在计算绑定时,尚未设置属性。

所以被绑定的属性是这样的:

public List<DateTime> Dates
{
    get
    {
        var dateTimes = new List<DateTime>();
        for (var currentDate = StartDate; currentDate <= EndDate; currentDate = currentDate.AddDays(1))
            dateTimes.Add(currentDate);
        return dateTimes;
    }
}

public List<int> Weeks
{
    get
    {
        var weeks = new List<int>();
        if (DateTimeFormatInfo.CurrentInfo != null)
        {
            var cal = DateTimeFormatInfo.CurrentInfo.Calendar;

            foreach (var dateTime in Dates)
            {
                var weekNum = cal.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
                if (weeks.All(f => f != weekNum))
                {
                    weeks.Add(weekNum);
                }
            }
        }
        return weeks;
    }
}

在 XAML 中,它绑定了 DATES 和 WEEKS 属性。但它们取决于首先设置的 StartDate 和 EndDate。

如何确保属性在绑定时已设置。或者有更好的方法吗?

【问题讨论】:

  • 什么?我在您的代码中看不到任何绑定。此外,如果属性不是 DependencyProperties,则无法绑定它们。请解释清楚
  • 我很抱歉 - 我已经尝试更好地解释了。

标签: wpf binding properties user-controls


【解决方案1】:

将您的 StartDate 和 EndDate 属性更改为 DependencyProperties 并在其属性更改回调中引发日期和周的属性更改事件:

How To Raise Property Changed events on a Dependency Property?

【讨论】:

  • “当你听到蹄声”...这样一个简单的解决方案,而且效果很好...谢谢。
猜你喜欢
  • 2011-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多