所以我在 WPF 中获得了一个 ListBox,在那里我通过 DataTemplate 在我的 ListBoxItem 中获得了一个 Button。我将像这样的按钮添加到我的项目中:
<ListBox Grid.Column="1" BorderBrush="Black" Margin="15,20,10,15" MinHeight="25" Name="tbxFiles"
VerticalAlignment="Stretch"
ItemsSource="{Binding Items}"
SelectionMode="Multiple">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="ListText" Text="{Binding}" Grid.Column="0"/>
<RadioButton Grid.Column="1" Content="TF" />
<RadioButton Grid.Column="2" Content="AF" />
<ComboBox Grid.Column="3" Text="Periode" />
<Button Grid.Column="4" Click="RemoveMark_Click" Content="Delete" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
现在要创建的每个列表框项目都有一个删除按钮,当我按下这个按钮时,这个代码将开始删除这个项目:
PeriodeCombo.Items.Clear();
string required = tbxFiles.SelectedItems.Cast<string>().Aggregate((a, b) => a + b);
required = tbxFiles.SelectedItems.Cast<string>().Distinct()
.Aggregate((a, b) => a + b);
required = tbxFiles.SelectedItems.Cast<string>().Distinct()
.Aggregate((a, b) => a + ";" + b);
string[] words = required.Split(';');
foreach (var word in words)
{
temp1.Add(word);
}
for (int i = 0; i < temp1.Count; i++)
{
path.Remove(temp1[i]);
}
path.Remove(required);
tbxFiles.Items.Remove(tbxFiles.SelectedItem);
while (tbxFiles.SelectedItems.Count > 0)
{
tbxFiles.Items.Remove(tbxFiles.SelectedItems[0]);
}
并且此代码仅删除我单击的这些项目,它们已被选中。但是我现在想要做的是,我可以通过单击项目所在的删除按钮来删除项目而无需选择。所以当我点击删除按钮时,项目会被删除而无需点击该项目。我是如何改变我的代码才能让它工作的?
答案 0 :(得分:0)
在 RemoveMark_Click
中,第一个参数(通常称为 sender
并且类型为 object
)应该由您单击的 Button
表示,并且它的 DataContext 应该是您的集合项删除。
因此将 RemoveMark_Click 更改为诸如:
void RemoveMark_Click(object sender, RoutedEventArg args)
{
//TODO add null checks a/o exception handling
var uiElement = (Button)sender;
var dataItem = uiElement.DataContext;
tbxFiles.Items.Remove(dataItem);
}
一般来说,对于一个按钮来说,使用一个Command来执行想要的动作是比较常见和好的做法,因为这样你就可以把魔法放在ViewModel中了。 此外,为了让 listboxitem 有一个特殊的布局,设置数据模板 a/o 列表框的 itemcontainerstyle 通常就足够了,您不需要 覆盖控件模板,但当然您可以它会起作用。