Skip to main content
 首页 » 编程设计

c#之MVVM 基金会 : Assertion Failed Error: Invalid Property Name

2024年02月24日18虾米姐

我刚刚开始使用 MVVM Foundation。我得到了

我的代码如下:

启动 View 模型

class StartViewModel : ObservableObject 
{ 
    public StartViewModel() { 
        _counter = 0; 
    } 
 
    public ICommand IncrementCommand 
    { 
        get { return _incrementCommand ?? (_incrementCommand = new RelayCommand(() => ++Counter)); } 
    } 
 
    protected int Counter {  
        get { return _counter; }  
        set { 
            _counter = value; 
            base.RaisePropertyChanged("Counter"); 
        } 
    } 
 
    protected int _counter; 
    protected RelayCommand _incrementCommand; 
} 

开始查看

<Grid> 
    <Grid.RowDefinitions> 
        <RowDefinition Height="50*" /> 
        <RowDefinition Height="250*" /> 
    </Grid.RowDefinitions> 
    <Button Content="Increment" Grid.Row="0" Command="{Binding IncrementCommand}" /> 
    <TextBlock Padding="5" Text="{Binding Counter}" Grid.Row="1" /> 
</Grid> 

代码有什么问题?当我尝试单击增量按钮时出现错误

请您参考如下方法:

在 RaisePropertyChanged 行上将基础更改为此。

基类没有一个叫Counter的属性

编辑:也许是因为您的属性(property)受到保护而不是公开

MVVM Foundation 的 ObservableObject 中的注释提到它正在验证公共(public)属性