OnPropertyChanged()无法在MVVM中运行

时间:2016-05-26 00:20:43

标签: c# wpf mvvm mahapps.metro

我搜索了同样问题的所有其他问题。但我找不到任何解决方案。

OnPropertyChanged 正在触发但控件未更新。我正在使用 Mahapps.Metro ProgressRing Control

查看代码

<controls:MetroWindow.Resources>
        <userObj:LoginViewLogic x:Key="UserData"/>
        <userObj:LoginViewLogic x:Key="LoginViewLogic"/>
    </controls:MetroWindow.Resources>

    <Grid>
        <Canvas>
            <controls:ProgressRing Name="ProgressRing"  Canvas.Left="133" Canvas.Top="154" Height="50" Width="35" IsActive="{Binding Source={StaticResource UserData},Path=UserData.IsProgressRingActive}"/>
        </Canvas>
    </Grid>

ViewModel代码

    public class LoginViewLogic {

    public LoginViewLogic() {

       _userData = new User(AppSettings.ReadCredentials(),(bool)loadedSettings); 
    }

    private User _userData;
    public User UserData
    {
        get { return _userData; }
        set { _userData = value; }
    }

    public async void Login() {

        _userData.IsProgressRingActive = true;
        var loginResult = await Stuff.Login(_userData);

        if (!loginResult) {
            MessageBox.Show("You have entered an invalid username or password",
                "Information", MessageBoxButton.OK, MessageBoxImage.Error);
            _userData.IsProgressRingActive = false;
        }
    }

型号代码

 public class User : INotifyPropertyChanged {

        private bool _isProgressRingActive;
        public bool IsProgressRingActive {

            get { return _isProgressRingActive; }
            set {
                _isProgressRingActive = value;
                OnPropertyChanged("IsProgressRingActive");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName) {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

2 个答案:

答案 0 :(得分:0)

你试过这个:

<controls:MetroWindow.Resources>
        <userObj:LoginViewLogic x:Key="LoginViewLogic"/>
    </controls:MetroWindow.Resources>

    <Grid>
        <Canvas>
            <controls:ProgressRing Name="ProgressRing"  Canvas.Left="133" Canvas.Top="154" Height="50" Width="35" IsActive="{Binding Source={StaticResource LoginViewLogic},Path=UserData.IsProgressRingActive}"/>
        </Canvas>
    </Grid>

所以你只是创建并绑定到一个LoginViewLogic类的实例?

答案 1 :(得分:-1)

您的viewmodel还应该引发 PropertyChanged 事件。 尝试使用以下代码。

public class LoginViewLogic : INotifyPropertyChanged
{
    public LoginViewLogic() 
    {
       _userData = new User(AppSettings.ReadCredentials(),(bool)loadedSettings); 
    }

    private User _userData;
    public User UserData
    {
        get { return _userData; }
        set { _userData = value; }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName) {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

}