【发布时间】:2011-02-21 01:17:46
【问题描述】:
似乎还没有人找到一种方法来将组合框项设置为使用 SelectedItem="Binding Property" 选中。
解决方案是在组合框项目源中的 ViewModel 对象中使用 IsSelected 属性吗?
【问题讨论】:
标签: wpf mvvm combobox set selecteditem
似乎还没有人找到一种方法来将组合框项设置为使用 SelectedItem="Binding Property" 选中。
解决方案是在组合框项目源中的 ViewModel 对象中使用 IsSelected 属性吗?
【问题讨论】:
标签: wpf mvvm combobox set selecteditem
我们成功绑定组合框的方法如下...
<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 执行此操作,该 CollectionView 具有内置的组合框支持的当前项目管理。 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>();
}
}
【讨论】:
我发现在组合框源代码中,selecteditem 是通过使用 list selectedindex 设置的 组合框使用
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 属性的项目或使用@ 在您的代码中获取它987654329@自己。
这对我来说很好。
【讨论】: