IgorStack
IgorStack

Reputation: 869

Set Source for MenuItem in XAML

I've a Menu with MenuItems which are bound to RegionTypeenum.
MenuItems should have checkmarks and I want to bound IsChecked to some ObservableCollection<bool> (VisibleRegions):

<ObjectDataProvider x:Key="enumData" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="target:RegionType"/>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

And Menu itself:

<Menu>
    <MenuItem Header="Choose item" ItemsSource="{Binding Source={StaticResource enumData}}">
        <MenuItem.ItemContainerStyle>
            <Style TargetType="MenuItem">
                <Setter Property="IsCheckable" Value="True"/>
                <Setter Property="IsChecked" Value="{Binding VisibleRegions, Mode=TwoWay}"/>
                <Setter Property="StaysOpenOnClick" Value="True"/>
            </Style>
        </MenuItem.ItemContainerStyle>
    </MenuItem>
</Menu>

VS Output tells me in runtime:

System.Windows.Data Error: 40 : BindingExpression path error: 'VisibleRegions' property not found on 'object' ''RegionType' (HashCode=0)'. BindingExpression:Path=VisibleRegions; DataItem='RegionType' (HashCode=0); target element is 'MenuItem' (Name=''); target property is 'IsChecked' (type 'Boolean')

The message is pretty clear but how do I correct this xaml piece?

Upvotes: 0

Views: 743

Answers (1)

Domysee
Domysee

Reputation: 12846

There is no straightforward way in xaml to get the current index when binding to a collection.

So, what you should do is to bind to an ObservableCollection of a class that combines the enum values with the bool (IsChecked). For example:

public class EnumData
{
    public string Enum { get; set; }
    public bool IsChecked { get; set; }
}


var enumData = new ObservableCollection<EnumData> (Enum.GetNames(typeof(YourEnum))
    .Select(s => new EnumData { Enum = s, IsChecked = false }));

And then just set the DisplayMemberPath to the property you want displayed:

<Menu>
    <MenuItem Header="Choose item" ItemsSource="{Binding enumData}" DisplayMemberPath="Enum">
        <MenuItem.ItemContainerStyle>
            <Style TargetType="MenuItem">
                <Setter Property="IsCheckable" Value="True"/>
                <Setter Property="IsChecked" Value="{Binding IsChecked, Mode=TwoWay}"/>
                <Setter Property="StaysOpenOnClick" Value="True"/>
            </Style>
        </MenuItem.ItemContainerStyle>
    </MenuItem>
</Menu>

Upvotes: 1

Related Questions