【发布时间】:2014-11-01 21:57:09
【问题描述】:
我有一个包含 3 个文件的小应用程序。第一个文件是Authentication,它继承自第二个文件ObservableObject。此文件继承INotifyPropertyChanged。
class Authentication : ObservableObject
{
public void Start()
{
Auth = Visibility.Visible;
Tab = Visibility.Collapsed;
}
public void SetView()
{
Auth = Visibility.Collapsed;
Tab = Visibility.Visible;
}
public Visibility Auth { get; set; }
public Visibility Tab { get; set; }
public Visibility Admin { get; set; }
public Visibility Planner { get; set; }
public Visibility WorkPrep { get; set; }
public Visibility Leader { get; set; }
public Visibility PreSet { get; set; }
public Visibility Measure { get; set; }
public Visibility Worker { get; set; }
}
我的第三个文件是我的 View 的 ViewModel。
class MainWindowViewModel : ObservableObject
{
private Authentication auth = new Authentication();
public MainWindowViewModel()
{
LogIn = new RelayCommand(() => auth.SetView(), () => (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)) ? false : true);
auth.Start();
}
public ICommand LogIn { get; set; }
public Visibility Auth
{
get
{
return auth.Auth;
}
set
{
auth.Auth = value;
NotifyPropertyChanged();
}
}
public Visibility Tab
{
get
{
return auth.Tab;
}
set
{
auth.Tab = value;
NotifyPropertyChanged();
}
}
}
现在,当我启动应用程序时,auth.Start(); 被正确执行并设置了正确的Visibility。当我按下绑定到Command LogIn 的Button 时,auth.SetView(); 被执行但Visibilities 没有更新。
我的结论是,当我加载应用程序时,Visibilities 设置正确,但一旦加载,它就不会从 Authentication 类更新为 MainWindowViewModel 类。
编辑:这是对这个问题可能很重要的 ObservableObject 类。
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
【问题讨论】:
-
您是否通过调试代码验证了您的结论?
-
@DanielKelley,是的。我检查了每个起作用的变量和属性。当我从
public MainWindowViewModel调用auth.Start();时,Visibilities设置正确。当我从LogIn Command调用 auth.SetView() (或常规按钮单击,没关系)时,Authentication类中的 2 个属性已设置,但MainWindowViewModel类中没有设置,它使用的值来自Authentication. -
@DanielKelley,只是想知道。只做
MainWindowViewModel中的视觉内容和Authentication中的逻辑内容会更“聪明”吗?然后使用Authentication中的事件(任何其他选项)直接设置MainWindowViewModel中的属性?我知道如果我在应用程序运行时在MainWindowViewModel中设置属性,它会起作用。
标签: c# binding inotifypropertychanged