コメント セクションからの私の要点を説明するために、メソッドを実装するUserControl
呼び出しがあるとします。WindowItem
Clone
<UserControl x:Class="WpfApplication1.WindowItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Button Content="Click me"/>
</Grid>
</UserControl>
複数のコレクションを保持するクラスを作成しますWindowItem
public class MainWindowViewModel
{
public MainWindowViewModel()
{
}
public ObservableCollection<WindowItem> FirstCollection { get; set; }
public ObservableCollection<WindowItem> SecondCollection { get; set; }
public ObservableCollection<WindowItem> ThirdCollection { get; set; }
}
また、データバインディングを介してコレクションにバインドされた、含まれるView
threeを作成しますListViews
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<ListView ItemsSource="{Binding FirstCollection}"/>
<ListView ItemsSource="{Binding SecondCollection}"/>
<ListView ItemsSource="{Binding ThirdCollection}"/>
</StackPanel>
</Grid>
</Window>
次に、MainWindow のコンストラクター ( として知られているView
) で、そのDataContextを以前に作成したクラス ( MVVMViewModel
で知られている) に設定します。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
これで、別のコレクションのユーザー コントロールのクローンを作成し、ビュー内の別のリストに表示してCollectionChanged
、最初のコレクションのイベントに登録できます。ViewModel コンストラクターからこれを行う例を次に示します。
public MainWindowViewModel()
{
FirstCollection = new ObservableCollection<WindowItem>();
SecondCollection = new ObservableCollection<WindowItem>();
ThirdCollection = new ObservableCollection<WindowItem>();
var windowItem = new WindowItem();
FirstCollection.Add(windowItem);
SecondCollection.Add(windowItem.Clone());
// Register to collection changes notifications
FirstCollection.CollectionChanged += FirstCollectionChanged;
}
FirstCollectionChanged
最初のコレクションが変更されるたびに発生します。削除アクションを「リッスン」してから、一致するアイテムを他のコレクションから削除できます。
private void FirstCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
// Remove matching item from second and third collection.
}
}
最初のコレクションからアイテムを削除することでテストできます
FirstCollection.RemoveAt(0);
お役に立てれば