したがって、この猫の皮を剥ぐには少なくとも2つの方法があります。
- 私の質問へのコメントでクレメンスによって説明されたようにしてください
- WPFメンターによるこの投稿のように行う
キャストする必要がないため、ソリューション1はイベントサブスクリプションにとってより自然なようです。また、IntelliSenseは、キャストなしで実装されたインターフェイスのクラスメンバーを表示しないため、ソリューション2では、実装されているインターフェイスを確認し、そこでイベントを確認する必要があります。各ソリューションのサブスクリプションは次のようになります。
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
// Solution 1, subscription:
xActionListView.ItemContainerGenerator.ItemsChanged +=
new ItemsChangedEventHandler(ActionLog_ItemsChanged);
// Solution 2, subscription:
((INotifyCollectionChanged)xActionListView.Items).CollectionChanged +=
new NotifyCollectionChangedEventHandler(ActionListView_CollectionChanged);
}
ただし、ソリューション2では、ハンドラーでイベント引数を使用する方が簡単です。
// Solution 1, handler:
private void ActionLog_ItemsChanged(object sender, ItemsChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
// Solution 1, scroll the new item into view
xActionListView.ScrollIntoView(
xActionListView.Items[e.Position.Index + e.Position.Offset]);
}
}
// Solution 2, handler:
private void ActionListView_CollectionChanged(
object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
// Solution 2, scroll the new item into view
xActionListView.ScrollIntoView(e.NewItems[0]);
}
}
状況によっては、一方のソリューションが他方よりも適切であるように見えます。必要なデータに基づいて、イベントデータをどちらか一方で使用する方が簡単な場合があります。