似乎還沒有人找到一種方法來將Selectedobject設置爲SelectedItem =「Binding Property」。MVVM,WPF:如何在組合框中選擇一個項目
解決方案是在組合框itemssource中的ViewModel對象中使用IsSelected屬性?
似乎還沒有人找到一種方法來將Selectedobject設置爲SelectedItem =「Binding Property」。MVVM,WPF:如何在組合框中選擇一個項目
解決方案是在組合框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,它具有內置的組合框支持的當前項目管理。 CollectionView有一個CurrentItem get屬性,您可以使用它來獲取當前選定的屬性。
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>();
}
}
」 ......不知道爲什麼你無法將數據綁定到ComboBox上的SelectedItem而不看到您的代碼....「 做一個容易谷歌它非常廣泛的問題。 CollectionView總是在我的情況下,此外,我可以也不會踢我的ObservableCollection
CollectionView可以是ObservableCollection的視圖,因此需要踢任何東西。你是什麼意思,CollectionView是總開銷?您是否在談論CollectionView在Current之外提供的其他功能,如過濾,分組和排序?我仍然不知道在combobox上綁定selecteditem的問題是什麼。 – 2010-05-18 20:51:57
我不需要一個CollectionView多數民衆贊成它;-)如果我想排序這是控制的工作,在我的情況下DataGrid具有此功能。 CollectionView對於不對列標題進行排序的列表視圖是好的。 – msfanboy 2010-05-19 19:09:46
這很奇怪。我可以發誓,我沒有,因爲我的一些博客瞭解它到底是什麼,你之前提出... 現在我又試了一次,它的工作:P 在我這個,如果有人有興趣XD 幫助與此同時//將新創建的Schoolclass設置爲UI控件中的選定索引 .. SelectedSchoolclassIndex =(Schoolclasses.Count!= 0)? Schoolclasses.Count - 1:0; – msfanboy 2010-05-22 10:04:53
剛剛有這個問題。我有兩個獨立的集合,並且忘記了equals操作符,所以當前項目是從另一個集合中挑選出來的,而不是從我從XAML綁定的集合中挑選出來的。所以實施等於是固定的問題。但是從同一個集合中選擇也解決了這個問題 – 2011-09-07 11:04:35