繁体   English   中英

WPF - 从 ListView.SelectedItem 获取绑定源 object

[英]WPF - Get bound source object from 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 和普通后端编码混合在一起,这使您的代码难以阅读和理解。

我相信有两种方法可以访问 object。 如果我得到你正确的要求。 您可以投射:

MyObject currentItem = lvMyListView.SelectedItem as MyObject; 

或对您的原始列表使用lvMyListView.SelectedIndex

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

但是,更好的方法是同时使用 MVVM 和数据绑定。 It's longer than I can write here but you create a view model object and bind the selected item property of the list to one of it's properties also your button would trigger an action in the view model class. 这是 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM