在我的列表视图中,我有三列,第一列显示为带有图像的文本,其余列仅显示文本。列表视图编码如下:
<TabItem x:Name="HistoryTab" Header="History" Style="{StaticResource TabStyle}">
<Grid>
<ListView x:Name="HistoryTabLv" HorizontalAlignment="Left" Height="164" Width="275" VerticalAlignment="Top" SelectionChanged="HistoryTabLv_SelectionChanged" SelectionMode="Single">
<ListView.View>
<GridView>
<GridViewColumn x:Name="TimeColumn" Header="Time" Width="85">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="-5,0,0,0">
<Image x:Name="Img" Height="12" Width="12" Source="{Binding Image}" Stretch="Uniform"/>
<TextBlock Text="{Binding Time}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="PhoneNumColumn" Header="Phone Number" Width="85" DisplayMemberBinding="{Binding PhoneNum}" />
<GridViewColumn x:Name="DirectionColumn" Header="Direction" Width="95" DisplayMemberBinding="{Binding Direction}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</TabItem>
如果操作说明为真,则相关数据将绑定到下面编码的每列。
private void HistoryTabLv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (myStatement == true)
{
var uri = new Uri(@"/Resources/time.png", UriKind.Relative);
myImg = new BitmapImage(uri);
DateTime myTime = DateTime.Now;
HistoryTabLv.Items.Insert(0, new { Image = myImg, Time = myTime.ToString("hh:mm:ss tt"), PhoneNum = calledNum,
Direction = "Called out" });
}
}
在winform中,如果我想获得所选行的第二列值,则其编码如下:(基于我搜索过的内容)
string secondCol = lv.SelectedItems[0].SubItems[1].Text;
我想获取所选行的第二列值(在我的情况下是PhoneNum列),我该如何在WPF中执行此操作。我尝试使用下面的代码,但它不起作用。请帮忙。
string myText = (string)((DataRowView)HistoryTabLv.SelectedItems[0])["PhoneNum"];
答案 0 :(得分:1)
在WPF中,ListViewItem
只是内容对象的包装器,SelectedItem(s)
与源集合中的项目类型相同,所以通常会将HistoryTabLv.SelectedItem
强制转换为该类型但因为,据我所知,你使用匿名类型会让它变得更加困难。我认为最简单的解决方法是使用dynamic
dynamic selectedItem = HistoryTabLv.SelectedItem;
var phoneNum = selectedItem.PhoneNum;
或
dynamic selectedItem = HistoryTabLv.SelectedItems[0];
var phoneNum = selectedItem.PhoneNum;
修改强>
如果你要为你的项目创建类,如
public class MyItemClass {
public string Image { get; set; }
public string Time { get; set; }
public string PhoneNum { get; set; }
public string Direction { get; set; }
}
并创建您的项目
new MyItemClass {
Image = myImg,
Time = myTime.ToString("hh:mm:ss tt"),
PhoneNum = calledNum,
Direction = "Called out"
}
然后您可以将SelectedItem(s)
投射到您的项目类,如
var selectedItem = (MyItemType)HistoryTabLv.SelectedItem