|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ContainsItemsConverter.cs" company="Catel development team">
// Copyright (c) 2008 - 2011 Catel development team. All rights reserved.
// </copyright>
// <summary>
// Converter that converts whether a collection contains items or not.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Windows.Data;
namespace Catel.Windows.Data.Converters
{
/// <summary>
/// Converter that converts whether a collection contains items or not.
/// </summary>
#if !SILVERLIGHT
[ValueConversion(typeof(IEnumerable), typeof(bool))]
#endif
public class ContainsItemsConverter : IValueConverter
{
/// <summary>
/// Convert the count of a collection to true or false, depending on whether the collection contains items.
/// </summary>
/// <param name="value">Values to check for. Both collections and arrays are supported.</param>
/// <param name="targetType">Not used.</param>
/// <param name="parameter">Not used.</param>
/// <param name="culture">Not used.</param>
/// <returns>True when at least 1 item is inside the collection or array, otherwise false.</returns>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Check if we have a valid value
if (value == null)
{
return false;
}
// Check if the value is a collection
ICollection collection = value as ICollection;
if (collection != null)
{
return (collection.Count > 0);
}
// Check if the value is an IEnumerable
IEnumerable enumerable = value as IEnumerable;
if (enumerable != null)
{
foreach (object obj in enumerable)
{
// We have at least 1 item
return true;
}
}
// Not supported, thus false
return false;
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
/// <remarks>
/// This method is not supported.
/// </remarks>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ConverterHelper.DoNothingBindingValue;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.