WPF如何绑定组合框

WPF如何绑定组合框

本文介绍了WPF如何绑定组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的组合框的字符串列表绑定,我想一旦窗口被加载它显示的默认值。

I am trying to bind my ComboBox to list of strings and I would like it to show default value once Window is loaded.

要做到这一点,我创建了一个ViewModel类,如:

To do that, I created a ViewModel class like:

namespace MyData
{
    class ViewModel
    {
        public ViewModel()
        {
            this.Name = "";
            this.Age = 0;
            this.Address = "";
            this.DateOfPurchase = DateTime.Now.AddDays(-30);
            this.CarModel = "VW"; //I want to set VW as default but options are Mazda, VW, Audi
        }

        public IEnumerable<String> CarModels
        {
            get
            {
                var carModels = new String[] {"Mazda", "VW", "Audi"};
                //CarModel = cars.FirstOrDefault(car => CarModel == "VW");  //this is not needed

                return carModels;
            }
        }

        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public DateTime DateOfPurchase { get; set; }
        public String CarModel { get; set; }
    }
}



然后我设定DataSource的窗口我的视图​​模型

Then I set DataSource of Window to my ViewModel

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.DataContext = new ViewModel();
}



最后,我想我的控件绑定到这些数据。我为我的除外组合框所有其他人这样做。我想它得到高配车型(马自达,大众,奥迪)作为ComboBoxItems,并默认为第二个这是大众曾经形式加载字符串数组。

Finally, I would like to bind my controls to this data. I have done so for all others except my ComboBox. I would like it to get the string array with models (Mazda, VW, and Audi) as its ComboBoxItems and to default to 2nd which is VW once form loads.

然后我在XAML绑定是这样的:

Then I bind it like this in my XAML:

<ComboBox Name="cbCarModels" SelectedItem="{Binding CarModel, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding CarModels}">

和这个作品!

推荐答案

关闭我的头顶

在XAML

<Combobox ItemsSource="{Binding Path=CarModels}", SelectedItem="{Binding SelectedCar}/>

您需要创建ViewModel.SelectedCar模型,将它设置在vm.ctor

You'll need to create ViewModel.SelectedCar model. Set it in vm.ctor

this.SelectedCar = Cars[1]

您可能必须添加路径= CarModels ,模式=双向来结合。

You might have to add Path=CarModels, Mode=TwoWay to binding.

这篇关于WPF如何绑定组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:20