views:

27

answers:

2

I have 4 buttons in grid which datacontext is set to an object which has property that indicates what button should be enabled (it's enumerable).

Currenty I have done this in code-behind so that when that specific property changes, it disables all but one depending on the value. It works, but I really don't like to put stuff like this to code-behind. There must be a way to do this in xaml?

I could make own style for all four buttons and then do this with data triggers, but I would prefer more generic approach: use same style for all buttons that somehow applies differently depending on, for example, a button name and value of the property.

Thanks in advance.

+1  A: 

You could use a MultiBinding to bind the IsEnabled property to a combination of the control's name and the property from your DataContext, and create a Style to apply it to all buttons in the Grid:

<Grid.Resources>
    <local:EqualsConverter x:Key="EqualsConverter"/>
    <Style TargetType="Button">
        <Setter Property="IsEnabled">
            <Setter.Value>
                <MultiBinding Converter="{StaticResource EqualsConverter}">
                    <Binding RelativeSource="{RelativeSource Self}" Path="Name"/>
                    <Binding Path="EnabledButtonName"/>
                </MultiBinding>
            </Setter.Value>
        </Setter>
    </Style>
</Grid.Resources>

And in code:

public class EqualsConverter
    : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return values.Length == 2 && object.Equals(values[0], values[1]);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}
Quartermeister
Woah. This is exactly what I was looking for. Thanks!
Juha
+1  A: 

You can create an association between the enum you've created and the buttons by having integer references to your enum values and giving those enum values as ConverterParameters for corresponding buttons.

For Eg:

The enum:

public enum myOptions
{
    value1 = 1,
    value2 = 2,
    value3 = 3,
    value4 = 4
}

The Binding:

<Button IsEnabled = {Binding Path=myProperty, 
                             Converter = {StaticResource EnumToBoolConverter}, 
                             ConverterParameter = 1} />
<Button IsEnabled = {Binding Path=myProperty, 
                             Converter = {StaticResource EnumToBoolConverter}, 
                             ConverterParameter = 2} />

And the Converter:

public class EnumToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (int)value == (int)parameter;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}
Veer