ComboBox with an ItemTemplate that includes a button

So, let's say I have a ComboBox with a custom data template. One of the elements of the data template is the button:

<ComboBox Width="150" ItemsSource="{Binding MyItems}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Button Content="ClickMe" /> 
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

The problem is that the button eats a click and the item is not selected if the button is selected. This means that the pull does not disappear and the item is not selected.

I WHY this is happening.

Is there any way around this? Perhaps a way to handle the click of a button (I attach to the command) and tell her to continue the chain so that the combo box can also handle the click?

Note. I see my problem in Silverlight, but I assume that exactly the same behavior can be seen with WPF.

+3
4

SelectedItem .

+1

, . , Combo-box :

<ComboBox x:Name="MyCombo" Width="150" ItemsSource="{Binding MyItems}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Button Content="ClickMe" Click="Button_Click" /> 
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyCombo.SelectedItem = (sender as Button).DataContext;
    MyCombo.IsDropDownOpen = false;
}

, SelectedItem IsDropDownOpen ViewModel, HAM XAML, ViewModel .

+8

MVVM. ComboBox, adden, ButtonBase, Click, ComboBox.

, , , , .

public class MyComboBox : ComboBox
{
    public MyComboBox()
    {
        // use Loaded event to modify inital items.
        Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        if (Items != null)
        {
            foreach (var item in Items)
            {
                var button = item as ButtonBase;
                if (button != null)
                {
                    ModifyButtonItem(button);
                }
            }
        }
    }

    protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged(e);
        // Check added items. If an item is a button, modify the button.
        if (e.NewItems != null)
        {
            foreach (var item in e.NewItems)
            {
                var button = item as ButtonBase;
                if (button != null)
                {
                    ModifyButtonItem(button);
                }
            }
        }
    }

    private void ModifyButtonItem(ButtonBase button)
    {
        button.Click += (sender, args) => { IsDropDownOpen = false; };
    }
}
+1

, , . , , a Button ListBox, - Button ListBox. , ItemsControl, .

, - Click , , , .

0

Source: https://habr.com/ru/post/1708668/


All Articles