ItemsControl의 ItemsSource를 UIElements 또는 뷰의 ObservableCollection에 바인딩하거나 설정하는 것은 잘못되었습니다. 최소한 MVVM 디자인 패턴은 모든 XAML 기반 응용 프로그램에 사용할 권장 패턴입니다.
public class Job
{
}
public class JobViewModel
{
public ObservableCollection<Job> Jobs { get; } = new ObservableCollection<Job>()
{
new Job(),
new Job(),
new Job()
};
}
당신은 다음의 ItemsControl의 ItemTemplate을에 UserControl을 (JobView)를 사용 : 당신은 같은 객체의 ObservableCollection에에 JobView와 바인딩의 상태를 표현하는 클래스, 예를 만들어야합니다
장소에 이와
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new JobViewModel();
}
}
<ItemsControl ItemsSource="{Binding Jobs}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:JobView />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
당신은 다음 소스 모음에서 작업 클래스를 제거 뷰 모델의 명령 속성에 바인딩 JobView 클래스에 ICommand의 속성을 추가 할 수 있습니다. 다음 샘플 코드를 참조하십시오.
JobViewModel.cs :
public class JobViewModel
{
public JobViewModel()
{
RemoveCommand = new DelegateCommand<object>(argument =>
{
Jobs.Remove(argument as Job);
});
}
public ObservableCollection<Job> Jobs { get; } = new ObservableCollection<Job>()
{
new Job(),
new Job(),
new Job()
};
public DelegateCommand<object> RemoveCommand { get; }
}
JobView.xaml.cs :
public partial class JobView : UserControl
{
public JobView()
{
InitializeComponent();
}
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(JobView));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
}
JobView.xaml :
<UserControl x:Class="WpfApplication1.JobView"
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"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
x:Name="uc">
<UserControl.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" Command="{Binding PlacementTarget.Command, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}"/>
</ContextMenu>
</UserControl.ContextMenu>
<Grid>
<TextBlock>job view...</TextBlock>
</Grid>
</UserControl>
MainWindow.xaml :
<ItemsControl ItemsSource="{Binding Jobs}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:JobView Command="{Binding DataContext.RemoveCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
당신은 DelegateCommand 클래스를 직접 구현해야합니다 또는 당신은 프리즘 MVVM 도서관에서 사용할 수있는 하나를 사용할 수 있습니다 https://github.com/PrismLibrary/Prism/blob/master/Source/Prism/Commands/DelegateCommand.cs
프리즘 NuGet을 사용하여 설치할 수 있습니다
: https://www.nuget.org/packages/Prism.Wpf/합니다.
MVVM 패턴에 대한 자세한 내용은 https://msdn.microsoft.com/en-us/library/hh848246.aspx을 참조하십시오. XAML 응용 프로그램을 개발하는 경우 실제로 배우는 것이 좋습니다.