【发布时间】:2012-02-21 15:01:02
【问题描述】:
我正在尝试将我在 WinForms 中制作的小型原型应用程序迁移到 WPF。当我从下拉列表中选择不同的值时,WPF 中的组合框不会更改值,我遇到了一些问题。最初,我尝试仅复制我在 WinForms 应用程序中使用的代码来填充组合框并确定是否选择了新索引。这就是我的 WinForms 代码的样子:
private void cmbDeviceList_SelectedIndexChanged(object sender, EventArgs e)
{
var cmb = (Combobox) sender;
var selectedDevice = cmb.SelectedItem;
var count = cmbDeviceList.Items.Count;
// find all available capture devices and add to drop down
for(var i =0; i<count; i++)
{
if(_deviceList[i].FriendlyName == selectedDevice.ToString())
{
_captureCtrl.VideoDevices[i].Selected = true;
break;
}
}
}
在代码的前面部分,我通过循环可用设备并添加它们来填充_deviceList 列表和组合框(具体为Form1_Load)。我在 WPF 中尝试了相同的方法,只能填充组合框。当我选择一个新值时,由于某种原因,相同的确切值(初始设备)被发送到事件代码(我的 WPF 应用程序中的cmbCaptureDevices_SelectionChanged)。我四处寻找 WPF 中的一些教程,发现数据绑定可能是我的问题,于是我尝试了一下。这是我的 XAML 文件中的组合框:
<ComboBox ItemsSource="{Binding Devices}" Name="cmbCaptureDevices"
IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding CurrentDevice,
Mode=TwoWay}" Se;ectionChanged="cmbCapturedDevices_SelectionChanged" />
XAML 定义还有更多内容,但都是随意的东西,比如HorizontalAlignment 等等。我的VideoDevicesViewModel 继承自INotifyPropertyChanged,有一个private List<Device> _devices 和一个private Device _currentDevice。构造函数如下:
public VideoDevicesViewModel()
{
_devices = GetCaptureDevices();
DevicesCollection = new CollectionView(_devices);
}
GetCaptureDevices 只是我在 WinForms 应用程序中的循环,它使用当前机器上的所有可用捕获设备填充列表。我有一个public CollectionView DevicesCollection { get; private set; } 用于在应用程序开始时获取/设置设备。我当前设备的属性如下所示:
public Device CurrentDevice
{
get { return _currentDevice; }
set
{
if (_currentDevice = value)
{
return;
}
_currentDevice = value;
OnPropertyChanged("CurrentDevice");
}
}
OnPropertyChanged 仅在事件不为 null 时引发事件 PropertyChanged。我是 WPF 的新手(老实说,我对 C# 也很陌生)所以我不确定我是否遗漏了一些基本的东西。知道为什么这个组合框不会改变我的值吗?
【问题讨论】: