簡體   English   中英

WPF 列表框按鈕選中的項目

[英]WPF ListBox Button Selected Item

我有一個帶有一些文本塊和一個按鈕的列表框——在按鈕的代碼隱藏中,它調用一個方法來傳遞當前選定的列表框項目,這很好用。 問題是,當我 select 一個項目然后單擊另一個項目上的按鈕時,它不會更新“SelectedItem”屬性 - 有沒有辦法 Xaml 或 C# 我可以強制單擊按鈕 select 父 ListBoxItem?

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;

單擊一個Button時,它會將e.Handled設置為true,從而導致路由事件遍歷停止。

您可以向Button添加處理程序,再次引發路由事件,或者找到ListBoxItem類型的可視祖先,並將其IsSelected屬性設置為true。

編輯

像這樣的擴展方法:

public static DependencyObject FindVisualAncestor(this DependencyObject wpfObject, Predicate<DependencyObject> condition)
{
    while (wpfObject != null)
    {
        if (condition(wpfObject))
        {
            return wpfObject;
        }

        wpfObject = VisualTreeHelper.GetParent(wpfObject);
    }

    return null;
}

用法:

myButton.FindVisualAncestor((o) => o.GetType() == typeof(ListBoxItem))

您可以將ListBoxItem傳遞給命令參數。

XAML:

<ListBox.ItemTemplate>
    <DataTemplate>
        <Button Command="{Binding DataContext.DeleteItemCommand, ElementName=listBox}" CommandParameter="{Binding}"/>
    </DataTemplate>
</ListBox.ItemTemplate>

代碼:

    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM