[英]WPF ListBox Button Selected Item
I have a listbox with some textblocks and a button -- in the button's codebehind it calls a method passing the currently selected listbox item, this works great.我有一个带有一些文本块和一个按钮的列表框——在按钮的代码隐藏中,它调用一个方法来传递当前选定的列表框项目,这很好用。 The issue is that when I select an item and then click the button on another item it doesn't update the "SelectedItem" property -- is there a way Xaml or C# that I can force a button click to select the parent ListBoxItem?
问题是,当我 select 一个项目然后单击另一个项目上的按钮时,它不会更新“SelectedItem”属性 - 有没有办法 Xaml 或 C# 我可以强制单击按钮 select 父 ListBoxItem?
Xaml Xaml
<DataTemplate>
<Grid>
<Button x:Name="myButton" Click="myButton_Click" Height="30" Width="30">
<Image Source="Resources\Image.png" />
</Button>
<TextBlock Text="{Binding DataField}"></TextBlock>
</Grid>
</DataTemplate>
var curItem = ((ListBoxItem)myListBox.ContainerFromElement((Button)sender)).Content;
When a Button is clicked, it sets e.Handled to true, causing the routed event traversal to halt. 单击一个Button时,它会将e.Handled设置为true,从而导致路由事件遍历停止。
You could add a handler to the Button which raises the routed event again, or finds the visual ancestor of type ListBoxItem and sets its IsSelected property to true. 您可以向Button添加处理程序,再次引发路由事件,或者找到ListBoxItem类型的可视祖先,并将其IsSelected属性设置为true。
EDIT 编辑
An extension method like this: 像这样的扩展方法:
public static DependencyObject FindVisualAncestor(this DependencyObject wpfObject, Predicate<DependencyObject> condition)
{
while (wpfObject != null)
{
if (condition(wpfObject))
{
return wpfObject;
}
wpfObject = VisualTreeHelper.GetParent(wpfObject);
}
return null;
}
Usage: 用法:
myButton.FindVisualAncestor((o) => o.GetType() == typeof(ListBoxItem))
You can pass ListBoxItem
to the command parameters.您可以将
ListBoxItem
传递给命令参数。
XAML: XAML:
<ListBox.ItemTemplate>
<DataTemplate>
<Button Command="{Binding DataContext.DeleteItemCommand, ElementName=listBox}" CommandParameter="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
CODE:代码:
public ICommand DeleteItemCommand => new RelayCommand(obj => DeleteItem(obj));
private void DeleteItem(object obj)
{
if(obj is ItemName item)
Items.Remove(item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.