コンボボックスのあるウィンドウがあります。このコンボボックスには 5 つの ComboboxItems があります。
コード ビハインド ファイルで、SelectedItem (コンボボックス) を 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
}
}
(プロパティ Is Enabled を使用してこの問題を解決できることは承知していますが、ここでは説明しません)