Caliburn第2部分 数据绑定和事件

本文介绍使用Caliburn.Micro框架进行数据绑定和事件绑定的方法。包括如何在ViewModel中定义属性并实现自动更新UI,以及如何将View中的按钮事件与ViewModel中的方法关联起来。还介绍了如何通过实现事件警卫来限制某些操作的执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1.数据绑定

为ViewModel添加属性

public class AppViewModel : PropertyChangedBase
{
  private int _count = 50;
 
  public int Count
  {
    get { return _count; }
    set
    {
      _count = value;
      NotifyOfPropertyChange(() => Count);
    }
  }
}


在View中 添加一个TextBlock 

 

 注意:  Name="Count"             Caliburn提供的快捷数据绑定功能

For elements that display data such as TextBlock or TextBox, setting their name to match a property on the data model will automatically hook it up for you.

<Grid MinWidth="300" MinHeight="300" Background="LightBlue">
  <TextBlock Name="Count" Margin="20" FontSize="150" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>


 

 

 

 

2.事件绑定

 

为ViewModel添加方法

public void IncrementCount()
{
  Count++;
}


 

在View中 添加一个Button

 

注意  Name="IncrementCount"             Caliburn提供的快捷事件绑定功能

<Grid MinWidth="300" MinHeight="300" Background="LightBlue">
  <RepeatButton Name="IncrementCount" Content="Up" Margin="15" VerticalAlignment="Top" />
  <TextBlock Name="Count" FontSize="150" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>

 

 

3.事件警卫

When Caliburn Micro automatically hooks up the Click event to the IncrementCount method, it also looks for a method or property called CanIncrementCount.

通过添加一个CanIncrementCount方法或属性,您可以添加额外的逻辑,基于模型的当前状态决定事件是允许处理。

决定是否可以调用该方法

 

public bool CanIncrementCount
{
  get { return Count < 100; }
}


Since this logic is based on the value of the Count property, we also need to raise property change notification for the CanIncrementCount property whenever the Count value changes.

NotifyOfPropertyChange(() => CanIncrementCount);


Once the limit has been reached, the button will become disabled and prevent the user from further incrementing the value.


http://www.mindscapehq.com/blog/index.php/2012/1/16/caliburn-micro-part-2-data-binding-and-events/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值