开发者

Button-styled list-box doesn't seem to work

I have 2 listboxes in my app that use

<Window.Resources>
    <ItemsPanelTemplate x:Key="WrapPanelTemplate">
        <WrapPanel Width="290"/>
    </ItemsPanelTemplate>
    <DataTemplate x:Key="ButtonItemTemplate">
        <Button Content="{Binding Path=Name}" Width="120" Margin="3,2,3,2" />
    </DataTemplate>
</Window.Resources>

Everything looks great but when I try to click on them they do not select a new item. I have SelectedItem bound to a property on my view-model but whenever开发者_运维知识库 I select a new item the set method does not happen. I have a regular listbox that is hooked up in the same way and does work. Here is the implementation of the custom listbox:

<ListBox Height="284" HorizontalAlignment="Left" x:Name="faveProgramsButtons" 
    ItemsSource="{Binding Path=FavoriteAppList}" 
    SelectedItem="{Binding Path=FavoriteAppList_SelectedApp}" VerticalAlignment="Top" 
    Width="281" ItemsPanel="{StaticResource WrapPanelTemplate}"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
    ItemTemplate="{StaticResource ButtonItemTemplate}">
</ListBox>

Thanks!


The problem is that the Button is swallowing the mouse click so the ListBoxItem in the ListBox never receives it, hence it is never selected. If you want to be able to select the items when you click the Button you can try using a ToggleButton instead and bind IsChecked to IsSelected

<DataTemplate x:Key="ButtonItemTemplate">
    <ToggleButton Content="{Binding Path=Name}" Width="120" Margin="3,2,3,2" 
                  IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                                      Path=IsSelected,
                                      Mode=TwoWay}"/>
</DataTemplate>

You could also achieve this with a little code behind or an attached behavior.

ButtonItemTemplate

<DataTemplate x:Key="ButtonItemTemplate">
    <Button Content="{Binding Path=Name}" Width="120" Margin="3,2,3,2"
            Click="TemplateButton_Click"/>
</DataTemplate>

Code Behind

private void TemplateButton_Click(object sender, RoutedEventArgs e)
{
    Button clickedButton = sender as Button;
    ListBoxItem listBoxItem = GetVisualParent<ListBoxItem>(clickedButton);
    if (listBoxItem != null)
    {
        listBoxItem.IsSelected = true;
    }
}

public static T GetVisualParent<T>(object childObject) where T : Visual
{
    DependencyObject child = childObject as DependencyObject;
    // iteratively traverse the visual tree
    while ((child != null) && !(child is T))
    {
        child = VisualTreeHelper.GetParent(child);
    }
    return child as T;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜