是否值得使用触发器?如果您的集合(列表框、网格等)的任何 XAML 元素都绑定到在您的视图模型上公开集合的属性,您可以利用数据绑定和内置的 MVVM Light messenger 来通知您两者的属性更改以更 MVVM 友好的方式新旧值。这个例子不一定是特定于 WP7 的,但我认为它的工作原理是一样的。
例如,这可能是数据绑定集合:
public const string BillingRecordResultsPropertyName = "BillingRecordResults";
private ObservableCollection<BillingRecord> _billingRecordResults = null;
public ObservableCollection<BillingRecord> BillingRecordResults
{
get
{
return _billingRecordResults;
}
set
{
if (_billingRecordResults == value)
{
return;
}
var oldValue = _billingRecordResults;
_billingRecordResults = value;
// Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
RaisePropertyChanged(BillingRecordResultsPropertyName, oldValue, value, true);
}
}
我喜欢在我的 ViewModel 上公开一个属性,它是我要公开的任何集合的“选定项”。因此,对于 ViewModel,我将使用 MVVMINPC 片段添加此属性:
public const string SelectedBillingRecordPropertyName = "SelectedBillingRecord";
private BillingRecord _selectedBillingRecord = null;
public BillingRecord SelectedBillingRecord
{
get
{
return _selectedBillingRecord;
}
set
{
if (_selectedBillingRecord == value)
{
return;
}
var oldValue = _selectedBillingRecord;
_selectedBillingRecord = value;
// Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
RaisePropertyChanged(SelectedBillingRecordPropertyName, oldValue, value, true);
}
}
现在,如果您将 XAML 元素的 SelectedItem 绑定到这个公开的属性,它将在通过数据绑定在视图中选择时填充。
但更好的是,当您利用片段 MVVMINPC 时,您可以选择是否将结果广播给任何收听的人。在这种情况下,我们想知道 SelectedBillingRecord 属性何时发生变化。因此,您可以在 ViewModel 的构造函数中使用它:
Messenger.Default.Register<PropertyChangedMessage<BillingRecord>>(this, br => SelectedRecordChanged(br.NewValue));
在您的 ViewModel 的其他地方,无论您想要发生什么动作:
private void SelectedRecordChanged(BillingRecord br)
{
//Take some action here
}
希望这可以帮助...