【发布时间】:2016-05-23 20:29:16
【问题描述】:
标题说明了一切......
我的 DependencyProperty 的代码如下:
public object IsChecked
{
get { return GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(object),
typeof(MyCheckbox),
new PropertyMetadata(false, IsCheckedChanged));
private static void IsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var checkbox = d as MyCheckbox;
bool? newvalue = null;
if (e.NewValue is bool?)
newvalue = (bool?)e.NewValue;
else if (e.NewValue != null)
{
bool newbool;
if (!bool.TryParse(e.NewValue.ToString(), out newbool))
return;
newvalue = newbool;
}
if (checkbox != null && !checkbox.Checked.Equals(newvalue))
checkbox.Checked = newvalue;
}
我像这样绑定到该属性:
<local:MyCheckbox IsChecked="{Binding Stata,UpdateSourceTrigger=PropertyChanged}" />
Stata 是这样实现的:
private bool? _stata = null;
public bool? Stata
{
get { return _stata; }
set
{
_stata = value;
OnPropertyChanged();
}
}
当 Stata 更改为“true”时,MyCheckbox 会按预期更新。但是,当 Stata 以 null 开始或更改为 null 时,MyCheckbox 不会得到更新,IsCheckedChanged 不会触发。
如果我像这样将我的属性的默认值更改为 null:
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register("IsChecked",
typeof(object),
typeof(MyCheckbox),
new PropertyMetadata(null, IsCheckedChanged));
它再次按预期工作,每当Stata 更改为/从true/false 和null 时,都会调用IsCheckedChanged。
这是一个错误吗?我希望我的默认值为false,而不是null,我该如何实现呢?
编辑:我已将示例解决方案上传到 GitHub,而现在调用 Changed 函数,当值为 null 时,UWP 显示的结果不同
你可以在这里找到存储库:https://github.com/ManIkWeet/DependencyPropertyTest
【问题讨论】:
-
有什么理由将属性声明为
object而不是bool?。 -
是的,如果您将其声明为
bool?,则不能在XAML 中将其设置为{x:Type Null} -
您可能希望将其设置为
{x:Null},而不是{x:Type Null}。这对我来说非常适合bool?类型的属性。 -
你似乎是对的,但这仍然不能解决原来的问题。
-
看看这个:blog.jerrynixon.com/2014/07/…。够奇怪的……
标签: c# wpf properties uwp