问题
In my ListBox.ItemTemplate i have a TextBlock and a Remove button, the button must be enabled only if it's the last element o the listbox.
回答1:
Created a quick example for you. since you are want to use Button Control you can use Command to enable or disable your button.
View:
<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>
View Model:
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
I'm Just checking if the content of the Button is the last element of the list in CanExecute logic.so I'm passing that in CommandParameter binding. You can surely use the Index of listboxitem or just pass the whole item and compare that. it's the easiest way of doing this.
来源:https://stackoverflow.com/questions/34720553/only-enable-the-last-remove-element-button-of-a-listbox