Skip to content

Instantly share code, notes, and snippets.

@biac
Last active December 16, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biac/5500540 to your computer and use it in GitHub Desktop.
Save biac/5500540 to your computer and use it in GitHub Desktop.
バインドでも IsThreeState が有効になる ChackBox をでっち上げた f(^^; override できなかったので new した。ので、何かあっても知らんので、よろ (汗; プロパティの型を bool? にすると実行時にブチ落ちるのはなぜなんだぜ? orz
public class MyCheckBox : CheckBox
{
public new object IsChecked
{
get { return GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
public static new readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register("IsChecked", typeof(object), typeof(MyCheckBox),
new PropertyMetadata(null, new PropertyChangedCallback(OnIsCheckedChanged)));
private static void OnIsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var baseInstance = d as CheckBox;
if (e.NewValue == null)
{
if (baseInstance.IsChecked != null)
baseInstance.IsChecked = null;
return;
}
if (e.NewValue is bool)
{
var newValue = (bool)e.NewValue;
if(baseInstance.IsChecked != newValue)
baseInstance.IsChecked = newValue;
return;
}
var thisInstance = d as MyCheckBox;
bool value;
if (bool.TryParse(e.NewValue as string, out value))
thisInstance.SetValue(IsCheckedProperty, value);
else
thisInstance.SetValue(IsCheckedProperty, null);
}
public MyCheckBox()
{
base.IsChecked = null;
base.Checked += MyCheckBox_Checked;
base.Unchecked += MyCheckBox_Unchecked;
base.Indeterminate += MyCheckBox_Indeterminate;
}
void MyCheckBox_Indeterminate(object sender, RoutedEventArgs e)
{
this.IsChecked = null;
}
void MyCheckBox_Unchecked(object sender, RoutedEventArgs e)
{
this.IsChecked = false;
}
void MyCheckBox_Checked(object sender, RoutedEventArgs e)
{
this.IsChecked = true;
}
}
@biac
Copy link
Author

biac commented May 2, 2013

XAML側でTrue/Falseを指定しないなら、IsCheckedの型をbool?に変更してもOK。
 
DependencyPropertyはtypeof(object)じゃないとダメ。
http://danrigby.com/2012/07/24/windows-8-dev-tip-nullable-dependency-properties-and-binding/
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/e4e6bf30-0493-4ede-b20e-25a5d3ffe79e/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment