与INotifyPropertyChanged绑定仍然没有';t工作

本文关键字:工作 INotifyPropertyChanged 绑定 | 更新日期: 2023-09-27 18:26:44

尝试了很多东西,仍然不起作用。绑定两个TextBlock不起作用。使用的INotifyPropertyChanged接口很像这个代码,但没有用。

代码:

主窗口.xaml

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ClockWatcher" xmlns:System="clr-namespace:System;assembly=mscorlib"
        x:Name="clockWatcherWindow"
        x:Class="ClockWatcher.MainWindow"
        Title="Clock Watcher" Height="554" Width="949"
    KeyDown="KeysDown" Focusable="True" Closing="SaveSession"
    DataContext="{Binding SM, RelativeSource={RelativeSource Self}}">
    <TextBlock x:Name="programStartBlock" Text="{Binding StartTime, BindsDirectlyToSource=True, FallbackValue=Binding sucks so much!!!,  StringFormat=ProgramStarted: '{0'}, TargetNullValue=This thing is null}" Padding="{DynamicResource labelPadding}" FontSize="{DynamicResource fontSize}"/>
    <TextBlock x:Name="totalTimeLabel" Text="{Binding SM.currentSession.TotalTime, StringFormat=Total Time: '{0'}}" Padding="{DynamicResource labelPadding}" FontSize="{DynamicResource fontSize}"/>
</Window>

主窗口.xaml.cs

public partial class MainWindow : Window
{
    private const string SESSION_FILENAME = "SessionFiles.xml";
    /// <summary>
    /// Represents, during selection mode, which TimeEntry is currently selected.
    /// </summary>
    public SessionManager SM { get; private set; }
    public MainWindow()
    {
        InitializeComponent();
        SM = new SessionManager();
        SM.newAddedCommentEvent += currentTimeEntry_newComment;
        SM.timeEntryDeletedEvent += currentTimeEntry_delete;
        SM.commentEntryDeletedEvent += entry_delete;
    }
}

SessionManager.cs:

public class SessionManager : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        [NonSerialized]
        private DateTime _dtStartTime;
        private Session current_session;
        #region Properties
        public DateTime StartTime
        {
            get
            {
                return _dtStartTime;
            }
            private set
            {
                if (_dtStartTime != value)
                {
                    _dtStartTime = value;
                    OnPropertyChanged("StartTime");
                }
            }
        }

 public Session CurrentSession
    {
        get
        {
            return current_session;
        }
        set
        {
            if (current_session != value)
            {
                OnPropertyChanged("CurrentSession");
                current_session = value;
            }
        }
    }
        #endregion
        public SessionManager()
        {
            _dtStartTime = DateTime.Now;
        }
        private void OnPropertyChanged([CallerMemberName] string member_name = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(member_name));
            }
        }
    }

会话.cs

public class Session : INotifyPropertyChanged
    {
        private TimeSpan total_time;
        public DateTime creationDate { get; private set; }
        public event PropertyChangedEventHandler PropertyChanged;

        public TimeSpan TotalTime
        {
            get
            {
                return total_time;
            }
            set
            {
                if (total_time != value)
                {
                    OnPropertyChanged("TotalTime");
                    total_time = value;
                }
            }
        }
        public Session()
        {
            creationDate = DateTime.Now;
        }
        private void OnPropertyChanged([CallerMemberName] string member_name = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(member_name));
            }
        }
    }

与INotifyPropertyChanged绑定仍然没有';t工作

  1. 在第一个TextBlock中,而不是SM.StartTime,只写StartTime。

  2. 从第一个TB中删除ElementName。

  3. 将CurrentSession设为公共属性,您的CurrentSession现在是私有的。

  4. 在您的SessionManager ctor中,current_session = new Session();

  5. 从XAML中删除DataContext,在窗口构造函数中使用this.DataContext = SM;

  6. 如果你想在XAML中使用DataContext,

    <Window.DataContext>
       <local:SessionManager />
    </Window.DataContext>
    

标记正确的答案肯定是更好的方法,但我只是想更详细地解释为什么你发布的内容不起作用。

问题是,当您在MainWindow.xaml中编写DataContext={Binding SM, RelativeSource={RelativeSource Self}时,绑定是在MainWindow.xsaml.cs构造函数中执行行SM = new SessionManager();之前评估的。

如果您将SM的getter更改为:,您可以看到这一点

public SessionManager SM
{
    get { return new SessionManager();}
}

这基本上确保了当WPF评估绑定时,它将为SM属性获得一个实际对象,而不是null。

只是想也许这将有助于理解并减少下次的挫折感:)。按照您提出问题的方式,从技术上讲,您需要在MainWindow类上实现INotifyPropertyChanged,这是一个很大的禁忌。