VMMV使列表框项目处于选中状态(以蓝色背景色突出显示) [英] VMMV make listbox item selected (higlighted with blue background color)

查看:87
本文介绍了VMMV使列表框项目处于选中状态(以蓝色背景色突出显示)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UserControl中有一个列表框,它的项目由datatemplate呈现,包含按钮,文本块等.我设法单击按钮到Viewmodel并获取绑定的itemdata.现在我想列出选择的项目(以蓝色背景色突出显示)时, 单击内部的按钮.

I have a listbox inside UserControl , its items rendered by datatemplate, contains button, textblock so on. I managed to click button to Viewmodel and get bound itemdata . now I want to listbox item selected(higlighted with blue background color) when I click button inside .

我尝试了这段代码,但是出现了异常,

I tried this code,but got exception,

Command="{Binding ElementName=List_UserControl,
                               Path= DataContext.ButtonClick,
                               RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" 

这是执行此操作的正确方法吗?如果是相对来源有什么问题?

is this the right approch to do that? if it is what it wrong in relativesource?

我的数据模板位于资源字典中,而我的列表位于用户控件中.

my datatemplate in a resourcedictionary, and my list in a usercontrol.

有人可以帮我吗?

最诚挚的问候

Alimjan

推荐答案

我不太了解问题的确切背景.实现此目标的简单方法之一如下所示:

I don't really kown the exact context of the problem. One of the simple ways of achieving this will be something like the following

关键是IsSelected属性在ListViewItem类型上,该类型是列表框中每个项目的包装类.

The key is that the IsSelected property is on the ListViewItem type which is a wrapper class for every single item in the list box.

带有按钮的XAML数据模板

XAML data template with a button

        <DataTemplate ...
                <Button x:Name="GoButton" 
                        Margin="10, 2, 2, 2"
                        Command="{x:Static Local:ViewModel.GoCommand}" 
                        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}">
                    Go</Button>
        </DataTemplate>

命令代码

            public void Execute(object parameter)
            {
                ListViewItem item = parameter as ListViewItem;
                if(item == null)
                {
                    return;
                }

                item.IsSelected = !item.IsSelected;
            }

此致


这篇关于VMMV使列表框项目处于选中状态(以蓝色背景色突出显示)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆