我有一个 ItemsControl,它在每个项目中都有一个上移、下移和删除按钮(通过模板)。我的 ItemsControl 源绑定(bind)到项目集合,这些项目是模型 DataContracts/POCO(不是 VM)。
我在主页的 View 模型中附加了一个 Caliburn 消息处理程序。
<Button cal:Message.Attach="MoveUp($dataContext)" >Up</Button>
<Button cal:Message.Attach="MoveDown($dataContext)" >Down</Button>
我相信我必须明确使用 cal:Message.Attach 而不是依赖约定,因为我在我的 ItemTemplate 中。
查看型号:
ObservableCollection<Item> MyCollection = new ObservableCollection<Item>();
//Item class is simple -- only has a string Name property
public bool CanMoveUp(Item item)
{
var index = MyCollection.IndexOf(item);
return index > 0;
}
public void MoveUp(Item item)
{
var index = MyCollection.IndexOf(item);
if (index > 0)
{
MyCollection.Remove(item);
MyCollection.Insert(index - 1, item);
}
}
public bool CanMoveDown(Item item)
{
var index = MyCollection.IndexOf(item);
return index > -1 && index < class1.Count - 1;
}
public void MoveDown(Item item)
{
var index = MyCollection.IndexOf(item);
if (index > -1 && index < class1.Count - 1)
{
MyCollection.Remove(item);
MyCollection.Insert(index + 1, item);
}
}
第一项的向上按钮最初是禁用的。当我向下移动第一项时,第二项成为第一项,但它的向上按钮不会自动禁用。如何强制重新评估 CanMoveUp 保护方法?
最佳答案
在您的 MoveUp
和 MoveDown
方法,您可以通知 UI CanMoveUp/Down
的绑定(bind)已使用 NotifyOfPropertyChanged(() => this.CanMoveUp);
无效(或 this.CanMoveDown 视情况而定)。
这是假设您的 ViewModel 派生自 Screen
, Conductor
, 或 PropertyChangedBase
它应该。
更新
您要做的是重构代码以绑定(bind) SelectedItem
的ListBox
到您的 View 模型上的 Item
类型的属性.事实上,如果您的 ListBox
,Caliburn.Micro 会为您执行此操作。有一个 x:Name="Items"
例如,它将查找名为 SelectedItem
的属性。 (它还搜索其他约定)。然后,您的 CanMoveUp/Down
方法可以是属性而不是检查 SelectedItem
属性,因此您可以使用 NotifyOfPropertyChanged()
使这些绑定(bind)无效。
关于silverlight - Caliburn Micro 中保护方法的强制重新评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6614166/