Hỏi đáp

Chia sẻ kiến thức, cùng nhau phát triển

Command trong WPF không hoạt động

15:52 03-09-2021 326 lượt xem 3 bình luận

Cho mình hỏi sao Command DeleteStudent của mình không hoạt động vậy ạ?

XAML Code

<ListView ItemsSource="{Binding Students}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
                    <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Id}"/>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Id}"/>
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button Height="50" Content="Delete" Command="{Binding DeleteStudent}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
</ListView>

ViewModel

 public partial class MainWindow : Window
    {
        public List<Student> Students { get; set; }

        ICommand DeleteStudent = new RelayCommand(o => { MessageBox.Show("DeleteStudents"); }, o => true);

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }
    }

 

Bình luận

Để bình luận, bạn cần đăng nhập bằng tài khoản Howkteam.

Đăng nhập
Vo Tan Duc đã bình luận 18:28 03-09-2021
Theo mình nghĩ, bạn nên dùng ObservableCollection thay cho List
Cu Xin Author đã bình luận 15:57 03-09-2021

ViewModel của ICommand bây giờ là một Student rồi bạn.

  1. Bạn set x:Key cho ListView.
  2. Bắt sự kiện khởi tạo ListView.
  3. Set DataContext của ListView bằng this.

Câu hỏi mới nhất