代わりに使用してみてくださいSelectedValue
。これにより、表示されている動作が抑制されます
<ListBox SelectedValue="{Binding MySelectedItem}" />
SelectedItem
選択したアイテムがリストに見つからないSelectedValue
場合、選択を解除しないようですが、選択を解除しているように見えますが、理由はわかりません
このサンプル アプリで違いを確認できます。
xaml:
<Window x:Class="WpfApplication11.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="184" Width="208" x:Name="UI">
<StackPanel DataContext="{Binding ElementName=UI}">
<TextBlock Text="SelectedValue" />
<StackPanel Orientation="Horizontal" Height="60" >
<ListBox ItemsSource="{Binding MyItemSource1}" SelectedValue="{Binding MySelectedValue}" Width="100" />
<ListBox ItemsSource="{Binding MyItemSource2}" SelectedValue="{Binding MySelectedValue}" Width="100" />
</StackPanel>
<TextBlock Text="SelectedItem" />
<StackPanel Orientation="Horizontal" Height="60" >
<ListBox ItemsSource="{Binding MyItemSource1}" SelectedItem="{Binding MySelectedItem}" Width="100" />
<ListBox ItemsSource="{Binding MyItemSource2}" SelectedItem="{Binding MySelectedItem}" Width="100" />
</StackPanel>
</StackPanel>
</Window>
コード:
public partial class MainWindow : Window , INotifyPropertyChanged
{
private CustomObject _mySelectedItem;
private CustomObject _mySelectedValue;
private ObservableCollection<CustomObject> _items = new ObservableCollection<CustomObject>();
private ObservableCollection<CustomObject> _items2 = new ObservableCollection<CustomObject>();
public MainWindow()
{
InitializeComponent();
MyItemSource1.Add(new CustomObject { Name = "Stack" });
MyItemSource1.Add(new CustomObject { Name = "Overflow" });
MyItemSource2.Add(new CustomObject { Name = "Stack" });
MyItemSource2.Add(new CustomObject { Name = "Overflow" });
}
public ObservableCollection<CustomObject> MyItemSource1
{
get { return _items; }
set { _items = value; }
}
public ObservableCollection<CustomObject> MyItemSource2
{
get { return _items2; }
set { _items2 = value; }
}
public CustomObject MySelectedItem
{
get { return _mySelectedItem; }
set { _mySelectedItem = value; NotifyPropertyChanged("MySelectedItem"); }
}
public CustomObject MySelectedValue
{
get { return _mySelectedValue; }
set { _mySelectedValue = value; NotifyPropertyChanged("MySelectedValue"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
public class CustomObject
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}