Avlonia CombBox (ViewModels) 範例

Avlonia CombBox (ViewModels) 範例

Avlonia CombBox (ViewModels) 範例


資料來源: copilot


範例01.(XAML)

<StackPanel Margin="20">
    <ComboBox SelectedIndex="0" MaxDropDownHeight="100">
        <ComboBoxItem>Text Item 1</ComboBoxItem>
        <ComboBoxItem>Text Item 2</ComboBoxItem>
        <ComboBoxItem>Text Item 3</ComboBoxItem>
        <ComboBoxItem>Text Item 4</ComboBoxItem>
        <ComboBoxItem>Text Item 5</ComboBoxItem>
    </ComboBox>
</StackPanel>

範例01.(Code)

using Avalonia.Controls;
using Avalonia.Media;
using System.Linq;

namespace AvaloniaControls.Views
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            fontComboBox.Items = FontManager.Current.GetInstalledFontFamilyNames()
                .Select(x => new FontFamily(x))
                .OrderBy(x => x.Name);
            fontComboBox.SelectedIndex = 0;
        }
    }
}


====================


範例02.(XAML)

<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"
        xmlns:vm="clr-namespace:YourNamespace.ViewModels"
        mc:Ignorable="d"
        x:Class="YourNamespace.Views.MainWindow"
        DataContext="{Binding MainWindowViewModel}">

    <StackPanel Margin="20">
        <ComboBox Items="{Binding Cities}"
                  SelectedItem="{Binding SelectedCity}"
                  DisplayMemberPath="Name"/>
        <TextBlock Text="{Binding SelectedCity.Name}"/>
        <TextBlock Text="{Binding SelectedCity.Region}"/>
    </StackPanel>
</Window>


範例02.(Code)

public class City
{
    public string Name { get; set; }
    public string Region { get; set; }
}
using System.Collections.ObjectModel;
using ReactiveUI;

public class MainWindowViewModel : ReactiveObject
{
    private City _selectedCity;

    public MainWindowViewModel()
    {
        Cities = new ObservableCollection<City>
        {
            new City { Name = "Taipei", Region = "Northern Taiwan" },
            new City { Name = "Taichung", Region = "Central Taiwan" },
            new City { Name = "Tainan", Region = "Southern Taiwan" },
            new City { Name = "Kaohsiung", Region = "Southern Taiwan" }
        };
    }

    public ObservableCollection<City> Cities { get; }

    public City SelectedCity
    {
        get => _selectedCity;
        set => this.RaiseAndSetIfChanged(ref _selectedCity, value);
    }
}
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace YourNamespace.Views
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainWindowViewModel();
        }
    }
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *