c# wpf string で CurrentItem にバインドする際に問題があり、人のリストがあり、各人は 2 つのアイテムのうちの 1 つを持つことができます。リストで人を選択してから、コンボボックスでその項目を選択できます。
コンボボックスは Persons.CurrentItem.Item にバインドし、その人が選択したアイテムとして持っているものを表示します。しかし、私はそれを変更することはできません。というか、行った変更を維持することはできません。新しい人を選択するとすぐに元に戻ります。
XAML は次のようになります。
<!--This dose not work-->
<TextBox Height="23" HorizontalAlignment="Left" Margin="148,55,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=Persons.CurrentItem.Item.Name}"/>
<!--This works-->
<TextBox Height="23" HorizontalAlignment="Left" Margin="16,306,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text="{Binding Path=Persons.CurrentItem.Name}"/>
<!--This works, we do not bind to CurrentItem-->
<ListBox Height="274" HorizontalAlignment="Left" ItemsSource="{Binding Path=Persons2}" SelectedItem="{Binding Path=SelectedPerson}" Margin="292,26,0,0" Name="listBox2" VerticalAlignment="Top" Width="120" DisplayMemberPath="Name" />
<ComboBox Height="23" HorizontalAlignment="Left" ItemsSource="{Binding Path=Items}" SelectedItem="{Binding Path=SelectedPerson.Item}" Margin="431,26,0,0" Name="comboBox2" VerticalAlignment="Top" Width="120" DisplayMemberPath="Name"/>
</Grid>
ご覧のとおり、SelectedPerson として SelectedItem を持つ person2 を追加しました。これは正常に機能し、その機能を模倣したいのですが、現在のアイテムを使用したいです。
これは C# コードです。
// Selectable items
public List<Item> Items { get; set; }
// List of persons, we will bind to it's CurrentItem
public List<Person> Persons { get; set; }
// This works, we do not use CurrentItem
public List<Person> Persons2 { get; set; }
private Person _selectedPerson;
public Person SelectedPerson
{
get { return _selectedPerson; }
set
{
_selectedPerson = value;
NotifyPropertyChanged("SelectedPerson");
}
}
#region Constructo
public Window()
{
InitializeComponent();
DataContext = this;
// Populate Items
Items = new List<Item>
{
new Item {Name = "Hammer"},
new Item {Name = "Axe"}
};
// Populate persons
Persons = new List<Person>() { new Person { Name = "Lisa", Item = Items.FirstOrDefault()}, new Person { Name = "Kauf" } };
Persons2 = new List<Person>(Persons); // make a copy
}
#endregion
#region PropertyChangeHandler
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
#endregion
}
public class Item
{
public string Name { get; set; }
}
public class Person
{
public string Name { get; set; }
private Item _item;
public Item Item
{
get { return _item; }
set
{
// We only accass this if we do not bind to CurrentItem
_item = value;
}
}
}
この例をテストすると、Persons.CurrentItem.Name が機能することがわかりますが、Persons.CurrentItem.Item.Name は機能しません。アクセスのレベルで何かを見逃したことがありますか? CurrentItem の使用方法について見逃したことはありますか?
教えてくれてありがとう。