【问题标题】:WPF designer gives exception when databinding a label to a checkboxWPF 设计器在将标签数据绑定到复选框时出现异常
【发布时间】:2011-02-03 13:54:42
【问题描述】:

我确定这很愚蠢,但我正在玩数据绑定。我在表单上有一个复选框和一个标签。我要做的只是将标签的内容绑定到复选框的 IsChecked 值。

我所做的运行良好(没有编译错误并且按预期运行),但是如果我触摸 XAML 中的标签,设计器会抛出异常:

System.NullReferenceException 你调用的对象是空的。 在 MS.Internal.Designer.PropertyEditing.Editors.MarkupExtensionInlineEditorControl.BuildBindingString(布尔模式支持,PropertyEntry propertyEntry) 在

<Window x:Class="UnitTestHelper.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:FileSysCtls="clr-namespace:WPFFileSystemUserControls;assembly=WPFFileSystemUserControls"
    xmlns:HelperClasses="clr-namespace:UnitTestHelper"
    Title="MainWindow" Height="406" Width="531">
<Window.Resources>
    <HelperClasses:ThreestateToBinary x:Key="CheckConverter" />
</Window.Resources>
<Grid Height="367" Width="509">
    <CheckBox Content="Step into subfolders" Height="16" HorizontalAlignment="Left" Margin="17,254,0,0" Name="chkSubfolders" VerticalAlignment="Top" Width="130" IsThreeState="False" />
    <Label Height="28" HorizontalAlignment="Left" Margin="376,254,0,0" Name="lblStepResult" VerticalAlignment="Top" Width="120" IsEnabled="True" Content="{Binding IsChecked, ElementName=chkSubfolders, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource CheckConverter}}" />
</Grid>

ThreeStateToBinary 类如下:

    class ThreestateToBinary : IValueConverter
{

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((bool)value)
            return "Checked";
        else
            return "Not checked";
        //throw new NotImplementedException();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return ((string)value == "Checked");
        //throw new NotImplementedException();
    }

    #endregion
}

老实说,我现在正在玩弄它。它最初更简单(不使用 ValueConverter),但当我将内容设置为时显示类似的行为:

Content="{Binding IsChecked, ElementName=chkSubfolders, UpdateSourceTrigger=PropertyChanged}" 

有什么想法吗?

谢谢,

约翰

【问题讨论】:

    标签: data-binding c#-4.0 binding


    【解决方案1】:

    尝试删除UpdateSourceTrigger=PropertyChanged。在这种情况下,复选框是您的来源,标签是您的目标。标签不会改变,此外,您将模式设置为OneWay,它将 only 从源绑定到目标。因此,告诉它在属性更改时更新源的绑定是没有意义的。它可能不会导致您的问题,但看起来很可疑(或至少很奇怪)。

    【讨论】:

    • 谢谢,本尼。当我发布时,这通常是我的问题......我尝试了很多变化,我不记得它最初的样子。唉,它并没有解决问题。
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2011-04-14
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多