【问题标题】:Button-styled list-box doesn't seem to work按钮样式的列表框似乎不起作用
【发布时间】:2011-08-01 20:48:59
【问题描述】:

我的应用中有 2 个列表框使用

<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>

一切看起来都很棒,但是当我尝试单击它们时,它们并没有选择新项目。我已将 SelectedItem 绑定到我的视图模型上的一个属性,但是每当我选择一个新项目时,set 方法都不会发生。我有一个常规的列表框,它以相同的方式连接并且可以正常工作。下面是自定义列表框的实现:

<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>

谢谢!

【问题讨论】:

    标签: c# wpf xaml listbox


    【解决方案1】:

    问题是Button 吞下了鼠标点击,所以ListBox 中的ListBoxItem 永远不会收到它,因此它永远不会被选中。如果您希望在单击Button 时能够选择项目,您可以尝试使用ToggleButton 并将IsChecked 绑定到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>
    

    您也可以通过后面的一些代码或附加的行为来实现这一点。

    ButtonItemTemplate

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

    代码背后

    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;
    }
    

    【讨论】:

    • 感谢您的回答。我明天上班时必须检查一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2012-02-16
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多