我的项目中有以下课程,
public class Area
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ObservableCollection<VisitDetail> VisitDetails { get; set; }
}
public class VisitDetail
{
[Key]
public int VisitId { get; set; }
[Required]
public int AreaId { get; set; }
public Area Area { get; set; }
}
用户希望使用以下方法将他们的访问区域保存为日期。
我只想从选择的中获得保存它们的ListView
。当我试图让那些使用ListView.Items[index].IsSelected
的人时,它会抛出一个错误,
Unable to cast object of type 'Namespace.Area' to type 'System.Windows.Controls.ListViewItem'
请告诉我解决问题的确切方法。
编辑1 :
我的项目在WPF。请注意,当访问详细信息窗口加载时,Area
实体集合被限制在ListView.ItemsSource
上。(由于WPF没有任何ListView.CheckedItems
:(
)
编辑2 :
谢谢你的解决方案奏效了。但我拿不到检查过的东西。我在这里发我的xaml。然而,我可以得到选定的项目。如果我能拿到那些检查过的东西,我会很高兴的。
这是我的ListView
的XAML
<ListView Name="lvList" SelectionMode="Multiple" ClipToBounds="True" >
<ListView.View>
<GridView >
<GridViewColumn DisplayMemberBinding="{Binding Id}" />
<GridViewColumn Header="Area" >
<GridViewColumn.CellTemplate>
<DataTemplate >
<CheckBox x:Name="checkbox" Content="{Binding Name}" IsChecked="{Binding Path=IsSelected}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
我认为我的问题应该有一个解决办法。
发布于 2013-02-10 20:05:16
引发异常是因为您的项目属性实际上表示用于生成列表内容的项的列表(也就是说,它们不是ListViewItem类型,而是区域类型)。这正是WPF的操作方式,在本例中,您需要的是向底层的ItemsControl的ItemContainerGenerator请求与UI中的项相对应的ListViewItem。
XAML:
<ListView Name="listView1" />
代码(假设您已经设置了DataContext和ItemsSource的ListView等):
ListViewItem item = listView1
.ItemContainerGenerator
.ContainerFromIndex(0) as ListViewItem;
item.IsSelected = true;
如果您不知道/不关心列表中的索引,而是知道项目,那么另一种选择就是。
ListViewItem item = listView1
.ItemContainerGenerator
.ContainerFromItem(someAreaInstance) as ListViewItem;
对问题2的答复:
您确实应该更深入地研究MVVM模式,这将有助于您从一开始就避免这种情况,但是这里有一种方法可以实现您所追求的目标。首先,您可能需要一个助手方法,如下所示(未测试):
static FrameworkElement GetVisualDescendantByName(DependencyObject control, string name)
{
// Recurse
FrameworkElement el = null;
int nChildren = VisualTreeHelper.GetChildrenCount(control);
for (int i = 0; i < nChildren; i++)
{
var child = VisualTreeHelper.GetChild(control, i);
el = GetVisualDescendantByName(child, name);
if (el != null)
return el;
}
// See if control is a match
if (control is FrameworkElement)
{
el = control as FrameworkElement;
if (el.Name == name)
return control as FrameworkElemdent;
}
return null;
}
你可以做一些像..。
foreach (var item in lvList.Items)
{
var listItem = lvList.ItemContainerGenerator
.ContainerFromItem(item) as ListViewItem;
CheckBox cb = GetVisualDescendantByName(listItem, "checkbox") as CheckBox;
// Do stuff with CheckBox...
var myVar = cb.IsChecked;
}
https://stackoverflow.com/questions/14801515
复制相似问题