wpf 在 ItemsControl 中获取所选项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18456836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting selected item in ItemsControl
提问by WAQ
I have the following code which populates my user control in form of rows and column. The user control which is being populated contains Button, links, textbox etc. When a certain button is pressed on a particular User Control in a particular row/column, I need to know for which User Control that button was pressed. Here is the XAML that is populating the user controls in rows and columns
我有以下代码以行和列的形式填充我的用户控件。正在填充的用户控件包含按钮、链接、文本框等。当在特定行/列中的特定用户控件上按下某个按钮时,我需要知道按下该按钮的用户控件。这是在行和列中填充用户控件的 XAML
<ItemsControl ItemsSource="{Binding Templates}" Width="{Binding GridWidth}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="{Binding NumColumns}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column" Value="{Binding ColumnIndex}" />
<Setter Property="Grid.Row" Value="{Binding RowIndex}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
</ItemsControl>
Templates is basically a collection of UserControls that are being populated in Rows/Columns. Preferably I want to do this in ViewModel but solution in code behind for now will work as well.
模板基本上是填充在行/列中的 UserControl 的集合。最好我想在 ViewModel 中执行此操作,但现在代码隐藏的解决方案也将起作用。
回答by CKII
ItemsControl
can't select items, only present collections. Only a Selectoror one of it's descendants can select items.
ItemsControl
不能选择项目,只能显示收藏。只有Selector或其后代之一可以选择项目。
For your scenario, I think a ListViewwith GridViewwould fit. When the user would click a control in the line, the event would bubble to the ListView
and the item would get selected. You can override the default styles so it wouldn't display as selected line: WPF ListView turn off selection.
对于您的场景,我认为带有GridView的ListView适合。当用户单击行中的控件时,事件将冒泡到并且项目将被选中。您可以覆盖默认样式,使其不会显示为选定行:WPF ListView turn off selection。ListView