You should use a ValueConverter for this:
public class IsNewOrOrderedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
OrderStatus status = (OrderStatus)value;
return status == OrderStatus.New || status == OrderStatus.Ordered;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then use it as the converter in your xaml:
<TextBox Text="{Binding OrderedAmount}"
IsEnabled="{Binding OrderStatus, Converter={StaticResource IsNewOrOrderedConverter}"/>
Don't forget to declare the resource:
<App.Resources>
<myPrefix:IsNewOrOrderedConverter x:Key="IsNewOrOrderedConverter" />
</App.Resources>
http://msdn.microsoft.com/en-us/library/ms750613.aspx on declaring resources.
Parametrization
A single converter can be made parametrized so it can be reused for different order types.
The XAML would be like this:
<local:OrderStatusToBooleanConverter
StatusList="New,Ordered" x:Key="NewOrOrderedConverter" />
<local:OrderStatusToBooleanConverter
StatusList="Delivered" x:Key="DeliveredConverter" />
This requires some special tactics since there is no way by default to make it readable (with enum values separated by a comma). That's where we need a type converter:
public class StringToOrderStatusArrayConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value == null)
{
return new OrderStatus[0];
}
else
{
return (from s in value.ToString().Split(',')
select Enum.Parse(typeof(OrderStatus), s))
.OfType<OrderStatus>()
.ToArray<OrderStatus>();
}
}
}
The type converter converts the input string array of enum values separated by a comma into an array.
This array can then be fed into the ValueConverter
:
public class OrderStatusToBooleanConverter : IValueConverter
{
[TypeConverter(typeof(StringToOrderStatusArrayConverter))]
public OrderStatus[] StatusList { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
OrderStatus status = (OrderStatus)value;
return StatusList != null && StatusList.Contains(status);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}