views:

2674

answers:

3

So, lets say I have a ComboBox with a custom data template. One of the items in the data template is a button:

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

The problem with this is that the button eats the click, and the item does not get selected if the button is selected. This means that the pull-down does not go away, and no item is selected.

I get WHY this is happening.

Is there a way to work around it? Possibly a way to process the button click (I am binding to a command) and tell it to continue up the chain so the combo box can also process the click?

Note: I am seeing my problem in Silverlight, but I am guessing that the exact same behavior can be seen with WPF.

A: 

I don't know if there is a way to do what you want. If you were to put a Button in a ListBox, for example, the same behavior occurs - clicking the Button does not cause its item in the ListBox to be selected. In fact, this is the case for any control in an ItemsControl that supports selection.

You might be able to do something with the Click event and mark it as not handled so that it continues up the visual tree, but even then I'm not sure if that would work or not.

Andy
+1  A: 

Your best bet would probably be to set the SelectedItem in the button's command.

Bryan Anderson
Yeah, I considered that, but doing that does not dismiss the pull-down that the Combo Box creates.
Brian Genisio
There is also an IsOpen (or something very similar) property on ComboBoxes, you can set it to False. You might also be able to set Focusable="False" on the buttons and get it to happen automagically.
Bryan Anderson
Yeah, it ended up being a combination of the two. See my answer for a full solution, but I want to give you the cred points, so I am marking your answer as correct.
Brian Genisio
+2  A: 

OK, I got it figured out. It is a total hack, but it still lets me bind my command to the button and continue to have Combo-box behavior for selecting the item:

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

And in the code behind:

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

If I really wanted to, I could bind the SelectedItem and IsDropDownOpen to properties in my ViewModel but I decided against it to keep this behavior as a hack extension of the XAML, in an effort to keep my ViewModel clean.

Brian Genisio