CheckBoxList.axaml代码

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Height="300" Width="300"
         xmlns:local="using:AvaloniaUI.Demos.Book._19.StoreDatabase"
        x:Class="AvaloniaUI.CheckBoxListTest"
        Title="CheckBoxList">
    <Window.Styles>

        <!-- 为特定的 ListBox(Class = checkbox-list)设置多选模式 -->
        <Style Selector="ListBox.checkbox-list">
            <Setter Property="SelectionMode" Value="Multiple"/>
        </Style>

        <Style Selector="ListBox.checkbox-list ListBoxItem">
            <Setter Property="Margin" Value="2"/>
            <Setter Property="Template">
                <ControlTemplate TargetType="ListBoxItem">
                    <CheckBox
                        Focusable="False"
                        IsChecked="{TemplateBinding IsSelected, Mode=TwoWay}">
                        <ContentPresenter Content="{TemplateBinding Content}" />
                    </CheckBox>
                </ControlTemplate>
            </Setter>
        </Style>

    </Window.Styles>

    <Grid Margin="8" RowDefinitions="*,auto">

        <ListBox x:Name="lstProducts"
                 Classes="checkbox-list"
                 Grid.Row="0">

            <ListBox.ItemTemplate>
                <DataTemplate x:DataType="local:Product">
                    <TextBlock Text="{Binding ModelName}" />
                </DataTemplate>
            </ListBox.ItemTemplate>

        </ListBox>

        <Button Grid.Row="1"
                Margin="0,5,0,0"
                Click="cmdGetSelectedItems">
            Get Selected Items
        </Button>

    </Grid>
</Window>

CheckBoxList.axaml.cs代码

using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using AvaloniaUI.Demos.Book._19.StoreDatabase;
using Shares.Avalonia;

namespace AvaloniaUI;

public partial class CheckBoxListTest : Window
{
    private StoreDb1 db = new StoreDb1();
    public CheckBoxListTest()
    {
        InitializeComponent();
        lstProducts.ItemsSource = db.GetProducts();
        //this.Load("avares://Shares/Avalonia/Styles/Styles.axaml");
    }

    private void cmdGetSelectedItems(object? sender, RoutedEventArgs e)
    {
        if (lstProducts.SelectedItems?.Count > 0)
        {
            string items = "You selected: ";
            foreach (Product product in lstProducts.SelectedItems)
            {
                items += "\n  * " + product.ModelName;
            }
            MessageBox.Show(this,items);
        }
    }
}

运行效果

image

 

posted on 2026-01-05 06:54  dalgleish  阅读(17)  评论(0)    收藏  举报