microsoft / XamlBehaviors

This is the official home for UWP XAML Behaviors on GitHub.
MIT License
701 stars 112 forks source link

ComboBox SelectionChanged command handler is not fired. #240

Open sam-wheat opened 1 year ago

sam-wheat commented 1 year ago

Repo is here.

I got lucky and guessed a way to make ItemsControl work - my luck has run out with Combobox.

Templated control vs custom control : https://github.com/microsoft/microsoft-ui-xaml/issues/3371

Themes/Generic.xaml:

ItemsControl - works:

<ItemsControl x:Name="peopleItemsControl"
              ui:FrameworkElementExtensions.AncestorType="local:PeopleControl"
              ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=People}" >
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ToggleSwitch ui:FrameworkElementExtensions.AncestorType="local:PeopleControl" OnContent="{Binding Name}" OffContent="{Binding Name}" >
                <Interactivity:Interaction.Behaviors>
                    <Interactions:EventTriggerBehavior EventName="Toggled">
                        <Interactions:InvokeCommandAction 
                            Command="{Binding (ui:FrameworkElementExtensions.Ancestor).TogglePersonCommand, 
                            ElementName=layoutRoot, Mode=TwoWay}" 
                            CommandParameter="{Binding}">
                        </Interactions:InvokeCommandAction>
                    </Interactions:EventTriggerBehavior>
                </Interactivity:Interaction.Behaviors>
            </ToggleSwitch>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Combobox - does not work:

<ComboBox
    ui:FrameworkElementExtensions.AncestorType="local:PeopleControl"
    Width="150"
    DisplayMemberPath="Name"
    ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=People}" 
    SelectionChangedTrigger="Always" >

    <!--Command="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TogglePersonCommand}"-->
    <Interactions:EventTriggerBehavior EventName="SelectionChanged">
        <Interactions:InvokeCommandAction 
            Command="{Binding (ui:FrameworkElementExtensions.Ancestor).TogglePersonCommand, 
            ElementName=layoutRoot, Mode=TwoWay}"
            CommandParameter="{Binding SelectedItem}">
        </Interactions:InvokeCommandAction>
    </Interactions:EventTriggerBehavior>
</ComboBox>

PeopleControl.cs:

    TogglePersonCommand = new AsyncRelayCommand<object>(TogglePersonCommandHandler, (o) =>
    {
        return true; // never fired for combobox
    });