Fix bug in BoolToVisibilityConverter, causing exception with some argument types

This commit is contained in:
Antony Male 2014-07-21 11:20:29 +01:00
parent 1d9a5d4248
commit 092cf02599
2 changed files with 24 additions and 3 deletions

View File

@ -53,15 +53,30 @@ namespace Stylet.Xaml
{
bool result;
if (value == null)
{
result = false;
}
else if (value is bool)
{
result = (bool)value;
}
else if (value is IEnumerable)
{
result = ((IEnumerable)value).GetEnumerator().MoveNext();
else if (value.Equals(System.Convert.ChangeType((object)0, value.GetType())))
result = false;
}
else
result = true; // Not null, didn't meet any other falsy behaviour
{
// This fails if it an int can't be converter to it, or for many other reasons
// Easiest is just to try it and see
try
{
result = !value.Equals(System.Convert.ChangeType((object)0, value.GetType()));
}
catch
{
result = true; // Not null, didn't meet any other falsy behaviour
}
}
return result ? this.TrueVisibility : this.FalseVisibility;
}

View File

@ -129,6 +129,12 @@ namespace StyletUnitTests
Assert.AreEqual(Visibility.Visible, this.converter.Convert("hello", null, null, null));
}
[Test]
public void ConvertTreatsRandomObjectAsTrue()
{
Assert.AreEqual(Visibility.Visible, this.converter.Convert(typeof(int), null, null, null));
}
[Test]
public void ConvertBackThrowsIfTargetTypeIsNotBool()
{