我ComboBox
一个SourceUpdated绑定操作:撤消上一个ComboBox
<ComboBox
SourceUpdated="MyComboBox_SourceUpdated"
ItemsSource="{Binding ...}"
SelectedValue="{Binding Path=SelectedValueMember, NotifyOnSourceUpdated=True}"
SelectedValuePath="..."
DisplayMemberPath="..."
/>
而且我SourceUpdated
处理程序:
private void MyComboBox_SourceUpdated(object sender, DataTransferEventArgs args) {
if (/* user answers no to an 'are you sure?' prompt */) {
// TODO: revert ComboBox back to original value
}
}
我有难以恢复的组合框回到其原始值(在“ TODO“评论我上面的代码)。
我想是简单地改回在DataContext的SelectedValueMember的价值,假设第一和最明显的东西结合将更新组合框:
MyDataContext.SelectedValueMember = original_value;
当我做到这一点,在调试器我可以看到它确实正在更新SelectedValueMember值,但ComboBox不会变回 - 它保留在新值上。
任何想法?
AngelWPF的回答下面的作品,并可能是最整洁和清晰的方式。
我也不过,找到一个非显而易见的解决方案:只需通过将操作的第二UI线程通过BeginInvoke
手段
private void MyComboBox_SourceUpdated(object sender, DataTransferEventArgs args) {
if (/* user answers no to an 'are you sure?' prompt */) {
Dispatcher.BeginInvoke(new Action(() => {
MyDataContext.SelectedValueMember = original_value;
}));
}
}
,它的作品!我可能是错的,但我的直觉是为了避免绑定更新循环,直接在源/目标更新处理程序中的操作不会被绑定反应。
您是否在SelectedValueMember上提升'PropertyChanged'?或者它是一个'DependencyProperty'。 – Silvermind 2012-03-13 14:33:32
Yep一个PropertyChanged事件引发。如果我测试并连接一个简单的按钮,其唯一目的是更改MyDataContext.SelectedValueMember的值,那么源目标绑定工作正常,ComboBox更新。 – Ross 2012-03-13 14:41:09
这里有一个类似的问题和答案:http://stackoverflow.com/questions/2585183/wpf-combobox-selecteditem-change-to-previous-value/2709931#2709931。我认为Angel的答案可能是最好的,但如果你不想在绑定上使用显式模式,那么使用BeginInvoke也可以。 – NathanAW 2012-03-13 15:43:44