WPF - 从 ListView.SelectedItem 获取绑定的源对象



我有一个绑定到List<MyObject>集合的ListView项。MyObject有各种我想调用的方法,例如,当用户从ListView中选择一个项目,然后单击按钮以对该单个SelectedItem执行操作时。

XAML:

<ListView x:Name="lvMyListView">
<ListView.View>
<GridView>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding myProperty}"/>
</GridView>
</ListView.View>
</ListView>

法典:

// WPF window constructor
public MyWindow()
{
InitializeComponent();
List<MyObject> myItems = new List<MyObject>();
this.SourceInitialized += MyWindow_SourceInitialized;
lvMyListView.ItemsSource = myItems;
}
// MyObject definition
class MyObject : INotifyPropertyChanged
{
...
public string myProperty { get; set; }
public void DoSomething()
{
...
}
}
// Button event
private void myButton_Click(object sender, RoutedEventArgs e)
{
// MyObject currentItem = lvMyListView.SelectedItem;
// currentItem.DoSomething();
}

如何获取由ListView.SelectedItem表示的MyObject的实际实例? 感谢您的任何帮助。

我已经多次阅读了您的问题。在我看来,您将 MVVM 和普通后端编码混合在一起,这使您的代码难以阅读和理解。

我相信有两种方法可以访问该对象。如果我得到你问的没错。你可以投射:

MyObject currentItem = lvMyListView.SelectedItem as MyObject; 

或对原始列表使用lvMyListView.SelectedIndex

另请注意,如果未选择第一个选项,则可以null第二个选项,并且可以-1第二个选项,因此请相应地添加检查。

但是,更好的方法是完全使用 MVVM 和数据绑定。它比我在这里写的要长,但是您创建一个视图模型对象并将列表的选定项属性绑定到其属性之一,您的按钮也会触发视图模型类中的操作。这是更好的 WPF 编码方法。所以请检查一下。

//let me know if any bug come, make sure it's selectedItems.Count>0||!=-1
//using getting selected object in IList
IList rows = tbl_perListView.SelectedItems;
//OR accessing DataGridRow,datarow,DataRowView properties (but this method is dirty needs lot of extra code)
DataRowView row = (DataRowView)tbl_perListView.SelectedItems[0];
string s = row["name"].ToString();

最新更新