WPF Combobox绑定List<string>

在WPF中若需要绑定List<string>对象到ItemsSource属性,具体操作步骤:

1 生成水果类

Fruits.cs

namespace WpfApp1
{
    public class Fruits
    {
        public Fruits()
        {
            Items = new List<string>
            {
                "苹果",
                "梨",
                "桔子",
                "桃子"
            };
        }

        public List<string> Items { get; set; }
    }
}

2 修改XAML文件

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        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:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="150" Width="300">

    <Window.Resources>
        <local:Fruits x:Key="key_Fruits"/>
    </Window.Resources>
    <Grid>
        <ComboBox HorizontalAlignment="Left" DataContext="{StaticResource key_Fruits}" ItemsSource="{Binding Items}"  SelectedIndex="0" Margin="44,27,0,0" VerticalAlignment="Top" Width="120"/>

    </Grid>
</Window>

3 运行程序

运行界面

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
您好,关于您的问题,可以通过以下步骤实现: 1. 在 XAML 中定义一个 ComboBox 控件和一个 ListBox 控件,并将 ComboBox 绑定到一个 List<string>。 2. 在 ListBox 中使用 DataTemplate 定义 CheckBox 的显示方式,并将其绑定ListBox 的 ItemsSource 属性。 3. 在 ComboBox 的 SelectionChanged 事件中,获取选中的项,并将其在 ListBox 中对应的 CheckBox 设置为不可选中。 具体实现可以参考以下代码: XAML 代码: <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="450" Width="800"> <Grid> <ComboBox x:Name="comboBox" ItemsSource="{Binding Items}" SelectionChanged="ComboBox_SelectionChanged"/> <ListBox x:Name="listBox"> <ListBox.ItemTemplate> <DataTemplate> <CheckBox Content="{Binding}" IsChecked="{Binding IsSelected}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> C# 代码: public partial class MainWindow : Window { public List<string> Items { get; set; } public MainWindow() { InitializeComponent(); // 初始化 ComboBox 绑定的数据源 Items = new List<string> { "Item1", "Item2", "Item3", "Item4" }; DataContext = this; } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { // 获取选中的项 string selectedItem = comboBox.SelectedItem as string; // 将 ListBox 中对应的 CheckBox 设置为不可选中 foreach (var item in listBox.Items) { if (item.ToString() == selectedItem) { (item as CheckBox).IsEnabled = false; } else { (item as CheckBox).IsEnabled = true; } } } }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sdhongjun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值