数据与定时器实现绑定 [英] Data Binding with Timer Implementation

查看:110
本文介绍了数据与定时器实现绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想不通为什么这个定时器不显示信息。定时器操纵以法TimeEntry更新TextBlock的。结合似乎并没有工作,我不明白如何正确地做到这一点。我看了看MSDN网站。他们只给了基础:没有足够的

code:

TimeEntry.xaml.cs

 公共部分类TimeEntry:用户控件
{
    公共静态只读的DependencyProperty timeSpentProperty =
       DependencyProperty.Register(timeSpent的typeof(时间跨度)
       typeof运算(TimeEntry)
       新FrameworkPropertyMetadata(TimeSpan.Zero));    #区域属性
    公开时间跨度timeSpent
    {
        得到
        {
            返回(时间跨度)的GetValue(TimeEntry.timeSpentProperty);
        }
        组
        {
            的SetValue(TimeEntry.timeSpentProperty,值);
        }
    }
    #endregion    静态TimeEntry(){}    公共TimeEntry(INT ID)
    {
        的DataContext =这一点;
        this.InitializeComponent();
        // code
    }
}

TimeEntry.xaml

 <用户控件
    X:类=ClockWatcher.TimeEntry
    X:名称=用户控件>
    <电网X:NAME =LayoutRoot的Horizo​​ntalAlignment =左
        VerticalAlignment =评出的WIDTH ={DynamicResource creationWidth}
        HEIGHT ={DynamicResource creationHeight}>
        < TextBlock的X:名称=timeSpentBlock
            的Horizo​​ntalAlignment =左TextWrapping =包装
            文本={结合timeSpent,的ElementName =用户控件}
            VerticalAlignment =评出的填充={StaticResource的labelPadding}/>
    < /网格和GT;
< /用户控件>

SessionManager.cs

 公共类是SessionManager:INotifyPropertyChanged的
    {
        公共事件PropertyChangedEventHandler的PropertyChanged;
        [非序列化]
        私人定时器_timer;
        [非序列化]
        私人秒表_clockWatch;
        [非序列化]
        私人的DateTime _dtStartTime;
        私人会话current_session;
        公共字符串strStartTime
        {
            得到
            {
                返回_dtStartTime.ToString();
            }
            私人集合{}
        }        公共SessionManager(中间)
        {
            _clockWatch =新的秒表();
            _timer =新定时器(1000); //1秒
            _timer.Elapsed + = clockWatch_Elapsed;
            _dtStartTime = DateTime.Now;
            CurrentSession =新的Session();
        }        ///<总结>
        ///注册Timer.Elapsed事件
        ///(请参阅构造函数)
        ///< /总结>
        公共无效clockWatch_Elapsed(对象发件人,ElapsedEventArgs E)
        {
            如果(CurrentSession!= NULL)
            {
                //更新当前timeEntry的timespent变量
                如果(CurrentSession.currentTimeEntry!= NULL)
                {
                    CurrentSession.currentTimeEntry.timeSpent = _clockWatch.Elapsed;
                    calculateTotalTime();
                }
            }
        }
        私人无效OnPropertyChanged([CallerMemberName]字符串MEMBER_NAME =)
        {
            如果(的PropertyChanged!= NULL)
            {
                的PropertyChanged(这一点,新PropertyChangedEventArgs(MEMBER_NAME));
            }
        }
    }


解决方案

您必须改变这样的。因为你在做错误的方式。


  1. 你想想,哪个属性必须更新。你想要的属性是 timeSpent 。那么你的 TimeEntry 类必须实现 INotifyPropertyChanged的事件。


  2. timeSpent 属性没有必要依赖项属性。因为你的'过去'事件手动分配它。


  3. 您的XAML必须在你的类进行连接。换句话说,你的身体(XAML)必须有灵魂(类实例)。


  4. 在第3步现在,你简单绑定这样你已经绑定模式。


在这里输入的形象描述

第2步的说明(依赖属性)

您当前使用的手动分配。在你的情况没有必要依赖属性。

在这里输入的形象描述

如果你想使用像下面的图片,你的财产 timeSpent 必须依赖项属性。

在这里输入的形象描述

Can't figure out why this timer isn't displaying information. Timer rigged to method to update TextBlock in TimeEntry. Binding doesn't seem to work, and I don't understand how to do it properly. I've looked at the MSDN sites. They only give out the basics: not enough.

Code:

TimeEntry.xaml.cs:

public partial class TimeEntry : UserControl
{
    public static readonly DependencyProperty timeSpentProperty =
       DependencyProperty.Register("timeSpent", typeof(TimeSpan),
       typeof(TimeEntry),
       new FrameworkPropertyMetadata(TimeSpan.Zero));

    #region Properties
    public TimeSpan timeSpent
    {
        get
        {
            return (TimeSpan)GetValue(TimeEntry.timeSpentProperty);
        }
        set
        {
            SetValue(TimeEntry.timeSpentProperty, value);
        }
    }
    #endregion

    static TimeEntry() { }

    public TimeEntry(int id)
    {
        DataContext = this;
        this.InitializeComponent();
        //code
    }
}

TimeEntry.xaml:

<UserControl
    x:Class="ClockWatcher.TimeEntry"
    x:Name="UserControl">
    <Grid x:Name="LayoutRoot" HorizontalAlignment="Left"
        VerticalAlignment="Top" Width="{DynamicResource creationWidth}"
        Height="{DynamicResource creationHeight}">
        <TextBlock x:Name="timeSpentBlock"
            HorizontalAlignment="Left" TextWrapping="Wrap"
            Text="{Binding timeSpent, ElementName=UserControl}"
            VerticalAlignment="Top" Padding="{StaticResource labelPadding}"/>       
    </Grid>
</UserControl>

SessionManager.cs:

    public class SessionManager : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        [NonSerialized]
        private Timer _timer;
        [NonSerialized]
        private Stopwatch _clockWatch;
        [NonSerialized]
        private DateTime _dtStartTime;
        private Session current_session;
        public string strStartTime
        {
            get
            {
                return _dtStartTime.ToString();
            }
            private set { }
        }

        public SessionManager()
        {
            _clockWatch = new Stopwatch();
            _timer = new Timer(1000);//one second
            _timer.Elapsed += clockWatch_Elapsed;
            _dtStartTime = DateTime.Now;
            CurrentSession = new Session();
        }

        /// <summary>
        /// Registered to Timer.Elapsed Event
        /// (See constructor)
        /// </summary>
        public void clockWatch_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (CurrentSession != null)
            {
                //update the timespent variable of the current timeEntry
                if (CurrentSession.currentTimeEntry != null)
                {
                    CurrentSession.currentTimeEntry.timeSpent = _clockWatch.Elapsed;
                    calculateTotalTime();
                }
            }
        }
        private void OnPropertyChanged([CallerMemberName] string member_name = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(member_name));
            }
        }
    }

解决方案

You must change like this. Because you doing wrong way.

  1. Think about it, which property must update. Your wanted property is timeSpent. Then your TimeEntry class must implement INotifyPropertyChanged event.

  2. timeSpent property no need to Dependency Property. Because you assign it manually in 'elapsed' event.

  3. Your xaml must be connected with your class. In other words, your body(xaml) must have soul(class instance).

  4. You already bind model in step 3. Now you simple bind like this.

Explanation of step 2. (Dependency Property)

Your current usage is manually assignment. In your case no need dependency property

If you want to use like below image, Your property timeSpent must Dependency Property.

这篇关于数据与定时器实现绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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