繁体   English   中英

使用 INotifyPropertyChanged 和命令 c# wpf?

[英]Using INotifyPropertyChanged and commands c# wpf?

我尝试使用 INotifyPropertyChanged 界面,但不幸的是它没有与主 ui 连接。

// Declare the event
public event PropertyChangedEventHandler PropertyChanged;

private int _counter;

public int Counter
{
    get { return _counter; }
    set
    {
        _counter = value;
        OnPropertyChanged();
    }
}


protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

private ICommand _clickCommand;
public ICommand ClickCommand
{
    get
    {
        return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), () => CanExecute));
    }
}
public bool CanExecute
{
    get
    {
        // check if executing is allowed, i.e., validate, check if a process is running, etc. 
        return true;
    }
}

public void MyAction()
{
    Counter++;
}

.xaml 文件

<Window.DataContext>
    <local:viewmodel/>
</Window.DataContext>
<Grid>
    <Label Content="{Binding Counter}" HorizontalAlignment="Left" Margin="218,128,0,0" VerticalAlignment="Top"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="300,176,0,0" VerticalAlignment="Top" Width="75" Command="{Binding ClickCommand}"/>
</Grid>

我的想法是当我单击按钮时 => 应该将 1 添加到 counter.But ui 不更新。 我不知道如何使用命令和 INotifyPropertyChanged 更新 ui?

viewmodel class 应该实现INotifyPropertyChanged接口。

...
public class viewmodel : INotifyPropertyChanged
...

保持代码的 rest 不变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM