星想夜恋
2021-09-26 21:22
采纳率: 100%
浏览 35

wpf自定义控件报错:默认值类型与“IsChecked”属性的类型不匹配。

想写个WPF自定义控件,在里面加了一个checkbox,然后注册了一个依赖项用来暴露给外界以便于获取isChecked状态,现报错:
错误 XDG0062 默认值类型与“IsChecked”属性的类型不匹配。 FileOperator C:\Users\admin\source\repos\FileOperator\FileOperator\MainWindow.xaml 70

依赖项定义:

public Nullable<Boolean> CheckBoxIsChecked
        {
            get { return (Nullable<Boolean>)GetValue(CheckBoxIsCheckedProperty); }
            set { SetValue(CheckBoxIsCheckedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ChcckBoxIsChecked.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CheckBoxIsCheckedProperty =
            DependencyProperty.Register("IsChecked", typeof(Nullable<Boolean>), typeof(FileControl), new PropertyMetadata("CheckBox",new PropertyChangedCallback(onCheckBoxChanged)));

        static void onCheckBoxChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            ((FileControl)sender).OnCheckBoxValueChanged(args);
        }

        private void OnCheckBoxValueChanged(DependencyPropertyChangedEventArgs e)
        {
            bool temp = bool.Parse(e.NewValue.ToString());
            this.checkBox.IsChecked = (Nullable < Boolean >) temp;
        }

使用控件代码:

<local:FileControl />

  • 好问题 提建议
  • 收藏

1条回答 默认 最新

  • CSDN专家-showbo 2021-09-26 23:04
    已采纳
            public static readonly DependencyProperty CheckBoxIsCheckedProperty =
                DependencyProperty.Register("IsChecked", typeof(Nullable<Boolean>), typeof(FileControl), new PropertyMetadata("CheckBox", new PropertyChangedCallback(onCheckBoxChanged)));
    
    属性是Nullable<Boolean>类型,PropertyMetadata默认值题主传递了字符串,改为布尔值===>
    
    
            public static readonly DependencyProperty CheckBoxIsCheckedProperty =
                DependencyProperty.Register("IsChecked", typeof(Nullable<Boolean>), typeof(FileControl), new PropertyMetadata(false, new PropertyChangedCallback(onCheckBoxChanged)));
    

    有帮助麻烦点个采纳【本回答右上角】,谢谢~~

    已采纳该答案
    评论
    解决 1 无用
    打赏 举报

相关推荐 更多相似问题