簡體   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