使用SelectedValue
代替,這將吸乾你所看到的行爲嘗試
<ListBox SelectedValue="{Binding MySelectedItem}" />
看來,SelectedItem
不取消被選擇的項目沒有在列表中找到,但SelectedValue
似乎以取消選擇它,不知道爲什麼
你可以看到在這個示例應用程序的diffence:
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;
}
}
我認爲你應該使用一個自定義的附加行爲,而不是... –
@FelicePollano但我怎麼能做到這一點?你會有一些代碼來幫忙嗎? –
什麼是你的物品類型? – Clemens