我是C#新手,我正在尝试制作一个有两个按钮和一个标签的简单程序。按钮是" up"和" down",标签中的数字会根据它们而变化。当我执行程序时,label显示在viewmodel中定义的初始值。但是当我按下按钮时,它不会更新值。发生更新时,我无法确定哪些不起作用,按钮或标签。谢谢你的时间。
我认为问题在于使用" RaisePropertyChanged"。我不知道应该怎么用它。如果有人解释,那就好了。
视图中的按钮和标签:
<Button x:Name="Up" Content="Up" HorizontalAlignment="Left" Grid.Row="6" Grid.Column="1" VerticalAlignment="Top" Width="75" Grid.ColumnSpan="2" Command="{Binding UpCommand}"/>
<Button x:Name="Down" Content="Down" Grid.Column="3" HorizontalAlignment="Left" Grid.Row="6" VerticalAlignment="Top" Width="75" Command="{Binding DownCommand}" />
<Label x:Name="Number" HorizontalAlignment="Left" Height="31" Grid.Row="4" VerticalAlignment="Top" Width="161" Content="{Binding Path=Lol, UpdateSourceTrigger=PropertyChanged}" Background="#FFB95151" Grid.ColumnSpan="3" Grid.Column="1" />
这是ViewModel:
class MainViewModel : BaseINPC
{
//Number class to hold the number
private Number lol; //I'm not good at naming
public Number Lol
{
get
{
return lol;
}
set
{
lol = value;
RaisePropertyChanged("Lol");
}
}
public MainViewModel()
{
lol = new Number { number = 5 }; //initial value
RaisePropertyChanged("Lol");
}
#region Commands
//Up botton commands
void UpNumber()
{
lol.change(true); //it adds 1 to number when True, substracts 1 when false
RaisePropertyChanged("Lol");
}
bool CanUpNumber()
{
return true;
}
public DelegateCommand UpCommand { get { return new DelegateCommand(UpNumber, CanUpNumber); } }
//Down button
void DownNumber()
{
lol.change(false);
RaisePropertyChanged("Lol");
}
bool CanDownNumber()
{
return true;
}
public DelegateCommand DownCommand { get { return new DelegateCommand(DownNumber, CanDownNumber); } }
#endregion
}
这是在我的模型中:
class Number : INotifyPropertyChanged
{
private int _number;
public int number
{
get { return _number; }
set
{
_number = value;
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public void change(bool up)
{
if (up)
_number++;
else
_number--;
}
public override String ToString()
{
return "" + _number;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
答案 0 :(得分:2)
public void change(bool up)
{
if (up)
_number++;
else
_number--;
RaisePropertyChanged("number");
}
或
public int number
{
get { return _number; }
set
{
_number = value;
RaisePropertyChanged("number");
}
}
public void change(bool up)
{
if (up)
number++;
else
number--;
}
您缺少号码属性的通知
还将Label的内容绑定更改为Content="{Binding Path=Lol.number}"
,因为number是执行方法change()时实际更改的属性。
如果在运行时没有更改,可能不需要通知Lol,UpdateSourceTrigger = PropertyChanged与绑定到标签无关,所以也许删除它。