我有一个窗口与组合框。这个comboboxhas有5个ComboboxItems。绑定SelectedIndex(Combobox)不能从代码隐藏文件工作
我将SelectedItem(combobox)绑定到我的代码隐藏文件中的ComboBoxSelectedIndex属性。
在这个例子中我想,这是无法选择的项目4和5
,但我可以选择的项目4和5。有什么不对?
XAML代码:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStartupLocation="CenterScreen"
Height="350"
Width="500">
<StackPanel VerticalAlignment="Center">
<ComboBox SelectedIndex="{Binding Path=ComboBoxSelectedIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ComboBoxItem>Item 1</ComboBoxItem>
<ComboBoxItem>Item 2</ComboBoxItem>
<ComboBoxItem>Item 3</ComboBoxItem>
<ComboBoxItem>Item 4</ComboBoxItem>
<ComboBoxItem>Item 5</ComboBoxItem>
</ComboBox>
</StackPanel>
</Window>
代码隐藏文件:
namespace WpfApplication1
{
public partial class MainWindow : INotifyPropertyChanged
{
private int _selectedIndex;
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public int ComboBoxSelectedIndex
{
get { return _selectedIndex; }
set
{
if (value < 3)
{
_selectedIndex = value;
}
OnPropertyChanged("ComboBoxSelectedIndex");
Trace.WriteLine(ComboBoxSelectedIndex);
}
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
(我知道与属性已启用,我可以解决这个问题,但我也不是什么在这里)
哦..谢谢,我会尝试 – David 2012-08-10 07:15:54
我以前从未有这样的问题。只要绑定到SelectedItem就没有任何东西被解雇。另一种可能性是将itemssource绑定到http://msdn.microsoft.com/de-de/library/system.windows.data.collectionview.aspx,因此collectionview会包含selecteditem自动查看http:// msdn .microsoft.com/DE-DE /库/ system.windows.data.collectionview.currentitem.aspx – 2012-08-10 07:16:38