【发布时间】:2011-01-05 13:48:51
【问题描述】:
我遇到了与ObservableCollection 绑定的ComboBox 的问题,我想知道是否有人能指出我缺少的东西。
我有一个ComboBox,它绑定到一个简单的ObservableCollection<string>。我还将SelectedIndex 中的OneWay 绑定到某个属性。
在我的应用程序中,我想清除集合并用不同的数据重新填充它,并将SelectedIndex 设置为新值。由于某种原因,SelectedIndex 绑定不起作用。
我附上这个问题的一点重现:
public partial class Window1 : Window, INotifyPropertyChanged
{
private int j;
public event PropertyChangedEventHandler PropertyChanged;
public Window1()
{
InitializeComponent();
DataContext = this;
Tables = new ObservableCollection<string>();
}
public ObservableCollection<string> Tables { get; set; }
private int _TheIndex;
public int TheIndex
{
get { return _TheIndex; }
set
{
_TheIndex = value;
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("TheIndex"));
}
}
}
private void aaaa(object sender, RoutedEventArgs e)
{
j = (j + 1)%10;
Tables.Clear();
for(int i = 0; i < 10 ; i++)
{
Tables.Add(i.ToString());
}
TheIndex = j;
}
}
xaml 是:
<Window x:Class="WpfApplication1.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">
<Grid>
<StackPanel>
<ComboBox x:Name="TablesCombobox"
ItemsSource="{Binding Tables}"
SelectedIndex="{Binding TheIndex, Mode=OneWay}"/>
<Button Content="asdasd" Click="aaaa"/>
</StackPanel>
</Grid>
</Window>
【问题讨论】:
-
有什么理由不只在 aaaa() 中设置 TablesCombobox.SelectedIndex 而不是 TheIndex?不确定为什么绑定不起作用。
-
我只是将您的复制代码复制/粘贴到 VS2010 Express Beta 2 中 - 它可以顺利运行...
标签: wpf combobox observablecollection selecteditem selectedindex