프로그래밍/WPF

[WPF] ItemControl에서 Item Index binding

흔한티벳여우 2021. 5. 11. 16:57
반응형

ItemControl 등에서 각 itemsSource에 있는 파일을 삭제 처리나 수정 처리 할 때, 방법에 따라 다양하지만 해당 ItemTemplate에 추가나 삭제 버튼을 만들어 처리하는게 일반적이다. 이때 해당 ItemsSource의  Index값을 가져와서 처리하는 방법을 알아보자.

 

ItemsControl을 이용한 List 화면

<ItemsControl ItemsSource="{Binding IP}" AlternationCount="20">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" 
                            Margin="0 0 1 0"
                            VerticalAlignment="Center"
                            HorizontalAlignment="Center"
                            Text="{Binding Path=.}">
                </TextBlock>
                <Button Grid.Column="1" Content="x"
                        Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.DeleteCommand}"
                        CommandParameter="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource Mode=TemplatedParent}}"
                    Width="30"/>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

ViewModel

class ConfigViewModel : DialogViewModelBase<DialogResults>
{
    private string _address;
    public string Address
    {
        get { return _address; }
        set { SetProperty(ref _address, value); }
    }

    public ObservableCollection<string> IP { get; set; }

    public DelegateCommand<object> DeleteCommand { get; private set; }

    private DataManager _dm;

    public ConfigViewModel()
    {
        _dm = DataManager.GetInstance();

        DeleteCommand = new DelegateCommand<object>(OnDeleteCommand);
        IP = new ObservableCollection<string>(_dm.GetConfig());
    }

    private void OnDeleteCommand(object index)
    {
        if ((int)index != -1)
        {
            IP.RemoveAt((int)index);
            _dm.SaveConfig(IP);
        }
    }
}

 

반응형