仅启用ListBox的最后一个删除元素按钮

时间:2016-01-11 11:36:48

标签: c# wpf listbox

在我的ListBox.ItemTemplate中,我有一个TextBlock和一个Remove按钮,只有当它是列表框的最后一个元素时才能启用该按钮。

1 个答案:

答案 0 :(得分:0)

为您创建了一个快速示例。由于您想要使用Button Control,您可以使用Command启用或禁用您的按钮。

查看:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <local:ParentViewModel />
</Window.DataContext>

<ListBox Width="400" Height="auto" ItemsSource="{Binding MyList,Mode=TwoWay}" >
    <ListBox.Style>
        <Style TargetType="{x:Type ListBox}">
            <Setter Property="ItemTemplate" >
                <Setter.Value>
                    <DataTemplate>
                        <Button Content="{Binding}" Padding="15,5" Margin="10,4"
                                Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}},Path=DataContext.RemoveButtonCommand}"
                                CommandParameter="{Binding}"
                                />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Style>
</ListBox>

查看型号:

 public class ParentViewModel : INotifyPropertyChanged
{

    public ParentViewModel()
    {
        MyList = new List<string>();
        MyList.Add("1");
        MyList.Add("2");
        MyList.Add("3");
        MyList.Add("4");
        MyList.Add("5");
        MyList.Add("6");
        RemoveButtonCommand = new RelayCommand(param => this.RemoveCommandAction(param), param => this.CanExecuteRemoveButtonCommand(param));
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private List<string> myList;

    public List<string> MyList
    {
        get { return myList; }
        set 
        { 
            myList = value;
            OnPropertyChanged("MyList");
        }
    }


    public RelayCommand RemoveButtonCommand { get; set; }

    public void RemoveCommandAction(object param)
    {
        MyList.Remove((string)param);
        MyList = new List<string>(MyList);
    }

    public bool CanExecuteRemoveButtonCommand(object param)
    {
        return MyList[MyList.Count - 1] == ((string)param);
    }
}

RelayCommand:

Copy from here

我只是检查Button的内容是否是CanExecute逻辑中列表的最后一个元素。所以我在CommandParameter绑定中传递了它。您肯定可以使用listboxitem的索引或只是传递整个项目并进行比较。这是最简单的方法。