用户代码WPF未处理InvalidOperationException

时间:2013-03-14 00:08:25

标签: c# wpf checkbox dispatcher ivalueconverter

我有一些WPF GUI(托管在WinForm中),它有多个CheckBoxes。每个IsChecked的默认值CheckBox需要来自某些背景数据中的不同布尔字段。背景数据中的每个布尔字段都映射到CheckBox中的VisualTree。因此,我将每个IsChecked的{​​{1}}属性绑定到CheckBox本身,并使用Converter在后台数据中获取相应的布尔值。这样CheckBox成为Converter函数的输入,以便Converter可以知道它在CheckBox中的位置,并在后台数据中查询正确的布尔字段。当用户更改VisualTree时,CheckBox事件处理程序会将值设置回背景数据中的布尔字段。 XAML是这样的:

Checked/Unchecked

转换器代码如下:

    <DataTemplate x:Key="ModuleWithEnableControl">
        <WrapPanel>
            <CheckBox Content="Enable" 
                      IsChecked="{Binding Path=., RelativeSource={RelativeSource Mode=Self}, Mode=OneTime, 
                                  Converter={StaticResource moduleEnableDisableConverter}
                                  }"
                      Checked="ModuleEnabled" Unchecked="ModuleDisabled"
                />
        </WrapPanel>
    </DataTemplate>

Checked处理程序代码如下:

class ModuleEnableDisableConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      System.Windows.Controls.CheckBox theBox = (System.Windows.Controls.CheckBox)value;
      //Here suppose to get the default value of the CheckBox
      //but just return true for now
      return true;
    }
}

当程序启动时,转换器首先运行,因为它返回ture,然后立即运行Checked处理程序 private void ModuleEnabled(object sender, RoutedEventArgs e) { MessageBoxResult result = MessageBox.Show("Enabled", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { //Check the sender (CheckBox)'s location in the VisualTree, //Do set the boolean field in the background data } return; } 。然后在处理程序中执行ModuleEnabled时出现问题,MessageBox.Show()窗口抱怨:

  

InvalidOperationException未被用户代码

处理

  

调度程序处理已暂停

但邮件仍在处理中。

如果我注释掉Popup行,程序将按预期执行。如果我没有将MessageBox.Show()绑定到IsChecked本身,也没有问题,CheckBox在用户更改MessageBox时完全显示。我想知道为什么事件处理程序中的CheckBox与绑定转换器有冲突?另外,有没有办法在使用绑定设置初始值时不触发Checked处理程序?

0 个答案:

没有答案