我遇到了与 aComboBox
绑定的问题ObservableCollection
,我想知道是否有人可以指出我所缺少的内容。
我有一个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;
}
}
xml是:
<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>