且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单击列表视图项内的按钮,在列表视图中选择项

更新时间:2023-11-29 22:24:28

试试这个..





Try this..


<ListView ItemsSource="{Binding Path=List}" ItemTemplate="{StaticResource ResourceKey=dt2}" SelectedItem="{Binding CurrentCustomerToBeShown}" IsSynchronizedWithCurrentItem="True">
            <ListView.Resources>
                <Style TargetType="ListViewItem">
                    <Style.Triggers>
                        <Trigger Property="IsKeyboardFocusWithin" Value="True">
                            <Setter Property="IsSelected" Value="True"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ListView.Resources>
        </ListView>


HI Mahesh感谢您的解决方案,每件事情都运转良好,但它不适用于第一项列表显示。第一个没有被点击按钮选中。



如何为TabControl应用相同的内容?



HI Mahesh thanks for the solution, every thing is working fine but it not working for the first item in the ListView. The first is not getting selected on clicking button.

How can I apply the same for a TabControl ?

<TabControl ItemsSource="{Binding CurrentlyShownCustomers}" SelectedItem="{Binding CurrentCustomer}" Grid.Column="1">
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <ListView ItemsSource="{Binding CurrentlyShownCustomers}">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding FirstName}"/>
                            <Button Height="20" Width="20" Content="X" Grid.Column="1" Command="{Binding RelativeSource={RelativeSource FindAncestor, 
                                AncestorType={x:Type TabControl}}, Path=DataContext.CloseTabItem}"/>
                        </StackPanel>
                    </ListView>
                </DataTemplate>
</TabControl>


你好



如果你不介意的话一些代码隐藏,这也完成了工作:

Hello

If you don't mind do some code-behind, this does the job too:
lb.PreviewMouseLeftButtonDown += (MouseButtonEventHandler)(
    (o, e) => {
        ListViewItem lbItem = UITools.FindAncestor<listviewitem>(e.OriginalSource as DependencyObject) as ListViewItem;
        bool isListViewItem = lbItem != null;
        bool isButtonClicked = UITools.FindAncestor<button>(e.OriginalSource as DependencyObject) is Button;
        if (isListViewItem )
        {
            if (isButtonClicked)
                lbItem.SetValue(ListBoxItem.IsSelectedProperty, true);
            else e.Handled = true; //Handled means will not pass to ListView for selection.
        }                    
    });



FindAncenstor方法: [ ^ ]


FindAncenstor method: from UITools.cs[^]

public static T FindAncestor<t>(DependencyObject obj) where T : DependencyObject
{
    while (obj != null)
    {
        T o = obj as T;
        if (o != null)
            return o;
        obj = VisualTreeHelper.GetParent(obj);
    }
    return default(T);
}</t>





问候

Joseph Leung



Regards
Joseph Leung