R – Strange XAML MenuItem DataBound ItemsSource Refresh Issue after empty ItemsSource

data-bindingitemssourcenetwpf

I have a XAML MenuItem DataBound ItemsSource that is working fine however there is a small issue. When I view the MenuItem and there is no databound items the ParentMenu will be disabled and it appears fine without binding errors (as expected the ItemsSource is empty). If the ObservableCollection is modified and an item added, the binding refreshes and the MenuItem appears. However the ItemContainerStyle doesn't upodate the MenuItem.Tag property to the databound value.

The MenuItem works fine as long as the ItemsSource never starts as empty or is never reduced to empty. Does anyone have any tips for such an issue? I would like to have the ItemsSource and ItemContainerStyle refresh correctly at all times even when the ItemsSource starts as empty

XAML is shown below:

<MenuItem x:Name="MenuItem" Header="Menu" ItemsSource="{Binding Source={StaticResource MenuItemViewSource}}" ItemTemplate="{StaticResource MenuDataTemplate}">
    <MenuItem.ItemContainerStyle>
        <Style TargetType="{x:Type MenuItem}">
            <Setter Property="Tag" Value="{Binding Path=ID, Source={StaticResource MenuItemViewSource}}"/>
            <Setter Property="Background" Value="Red"/>
            <Setter Property="Opacity" Value="0.5"/>
            <EventSetter Event="Click" Handler="MenuItem_Click"/>
        </Style>
    </MenuItem.ItemContainerStyle>
    <MenuItem.Style>
        <Style TargetType="{x:Type MenuItem}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </MenuItem.Style>
</MenuItem>

Best Answer

Just a guess, but have you tried binding to the ID of the underlying data without setting the binding's DataSource to the view source? Like this:

<Setter Property="Tag" Value="{Binding ID}"/>

A binding like that within a style should bind to the DataContext of the MenuItem itself, which is the item that the MenuItem represents. Binding back to the view source like you're doing might be confusing it.

Related Topic