目前看来还没有人找到一种使用SelectedItem="绑定属性"将ComboBoxItem设置为选择状态的方法。
解决方案是在ComboBox的ItemsSource中使用ViewModel对象内部的IsSelected属性吗?
目前看来还没有人找到一种使用SelectedItem="绑定属性"将ComboBoxItem设置为选择状态的方法。
解决方案是在ComboBox的ItemsSource中使用ViewModel对象内部的IsSelected属性吗?
我们成功绑定下拉框的方法如下...
<ComboBox
ItemsSource="{Binding Path=AllItems}"
SelectedItem="{Binding Path=CurrentItem, Mode=TwoWay}" />
<TextBlock Text="{Binding Path=CurrentItem, Mode=TwoWay}" />
class public ItemListViewModel
{
public ObservableCollection<Item> AllItems {get; set;}
private Item _currentItem;
public Item CurrentItem
{
get { return _currentItem; }
set
{
if (_currentItem == value) return;
_currentItem = value;
RaisePropertyChanged("CurrentItem");
}
}
}
不知道你的代码为什么不能将数据绑定到ComboBox的SelectedItem上。以下展示了如何使用CollectionView来实现这一点,因为该类具有内置的当前项管理功能,可以支持ComboBox。CollectionView具有一个CurrentItem属性,您可以使用它来获取当前选择的项。
XAML:
<Window x:Class="CBTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<ComboBox
ItemsSource="{Binding Path=Names}"
IsSynchronizedWithCurrentItem="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Text="{Binding Path=Names.CurrentItem}" />
</StackPanel>
</Window>
后台代码:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;
namespace CBTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new VM();
}
}
public class VM
{
public VM()
{
_namesModel.Add("Bob");
_namesModel.Add("Joe");
_namesModel.Add("Sally");
_namesModel.Add("Lucy");
Names = new CollectionView(_namesModel);
// Set currently selected item to Sally.
Names.MoveCurrentTo("Sally");
}
public CollectionView Names { get; private set; }
private List<string> _namesModel = new List<string>();
}
}
public object SelectedItem {
get {
int index = SelectedIndex;
return (index == -1) ? null : Items[index];
}
set {
int x = -1;
if (itemsCollection != null) {
//bug (82115)
if (value != null)
x = itemsCollection.IndexOf(value);
else
SelectedIndex = -1;
}
if (x != -1) {
SelectedIndex = x;
}
}
}
每次您通过代码设置Selecteditem
时,此方法始终返回-1
或null
。
x = itemsCollection.IndexOf(value);
它在组合框代码中报告为错误(82115)
因此,有效的方法是直接使用SelectedIndex
并将其绑定,而不是使用SelectemItem
属性。如果您想要从绑定到SelectedItem
属性中仅读取项目,则可以这样做,或者在您的代码中使用ItemsSource
本身获取它。
这对我来说很好用。