リストにアイテムを追加するには、TextBox
に文字列型のプロパティを作成し、ViewModel
プロパティが変更されたときに通知します。編集用に同様のプロパティを作成する必要があります。また、から選択したアイテムの現在のインデックスを保存する必要があります。ListView
string contactName;
public string ContactName
{
get
{
return contactName;
}
set
{
contactName = value;
OnPropertyChanged("ContactName");
}
}
private string editedName;
public string EditedName
{
get { return editedName; }
set
{
editedName = value;
OnPropertyChanged("EditedName");
}
}
private int selectedIndex;
public int SelectedIndex
{
get { return selectedIndex; }
set
{
selectedIndex = value;
OnPropertyChanged("SelectedIndex");
}
}
TextBoxe
とをビューに追加ListBox
し、バインディングを適用します。これは難しい部分です。からアイテムを選択する場合、選択したアイテムのListView
インデックスをSelectedIndexプロパティに保存する必要があるため、選択した連絡先名はTextBox
、値の編集に使用するものにバインドする必要があります。
<ListBox Name="contactNames" SelectedIndex="{Binding SelectedIndex}" ItemsSource="{Binding ContactNames}" SelectedItem="{Binding EditedName}" />
<TextBox Name="addNameTextBox" Text="{Binding ContactName}" />
<TextBox Name="editNameTextBox" Text="{Binding EditedName}" />
ボタンクリックを処理するCommandメソッドで、設定されたプロパティに基づいてアイテムを追加または編集するロジックを追加します。
if (EditedName != null && EditedName != string.Empty)
{
ContactNames[SelectedIndex] = EditedName;
EditedName = string.Empty;
}
else if (ContactName!=null && ContactName != string.Empty)
{
ContactNames.Add(ContactName);
ContactName = string.Empty;
}
リストをとして作成することを忘れないでくださいObservableCollection
。それ以外の場合、LisView
リストに加えられた変更については通知されません。
お役に立てれば。