首页 > 解决方案 > 如何使按钮执行不在 MainPage 中的方法

问题描述

我在 MainPage 中有一个按钮,我想执行另一个类(Shelf.cs)中存在的方法

我试着做 click="local:Button_click" (local = using:Shelf) ,它没有让我,一直想添加一个“新的事件处理程序”

MainPage.xaml 中的按钮:

<Button x:Name="AddBookButton" Width="150" Height="150" Margin="675,0,0,0" click="Button_click"> // this creates a new method inside MainPage

Shelf.cs 中的方法:

public async void Button_Click(object sender, RoutedEventArgs e)
    {
        StackPanel adddialog = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            Width = 484,
            FlowDirection = FlowDirection.RightToLeft
        };
        TextBox title = new TextBox
        {
            Header = "العنوان:",
            PlaceholderText = "عنوان الكتاب",
            Width = 156,
            Margin = new Thickness(0, 0, 8, 0),
            FlowDirection = FlowDirection.RightToLeft
        };
        TextBox author = new TextBox
        {
            Header = "المؤلف:",
            PlaceholderText = "مؤلف الكتاب",
            Width = 156,
            Margin = new Thickness(0, 0, 8, 0),
            FlowDirection = FlowDirection.RightToLeft
        };
        TextBox publisher = new TextBox
        {
            Header = "الناشر (اختياري):",
            PlaceholderText = "ناشر الكتاب",
            Width = 156,
            Margin = new Thickness(0, 0, 0, 0),
            FlowDirection = FlowDirection.RightToLeft
        };

        adddialog.Children.Insert(0, title);
        adddialog.Children.Insert(1, author);
        adddialog.Children.Insert(2, publisher);
        ContentDialog addFileDialog = new ContentDialog
        {
            Title = "أضف بيانات الكتاب الجديد",
            Content = adddialog,
            PrimaryButtonText = "إضافة",
            CloseButtonText = "إلغاء",
            FlowDirection = FlowDirection.RightToLeft,
            Width = 700
        };
        ContentDialogResult result = await addFileDialog.ShowAsync();

        if (result == ContentDialogResult.Primary)
        {
            Book book = new Book()
            {
                Title = title.Text,
                Author = author.Text,
            };
            try
            {
                book.Publisher = publisher.Text;
            }
            catch { }
            Books.Add(book);
            AddBookButton.Visibility = Visibility.Collapsed;
        }
    }
}

如何让它转到shelf.cs中的方法?或者可能将事件路由到那里?

标签: c#uwpuwp-xaml

解决方案


做到这一点(和其他事情)的最正确和最好的方法是将项目分为三层,通过创建 MVVM 模式并使用大量数据绑定。

您创建一个 AppViewModel 类(实现 INotifyProperyChanged),在 MainPage.cs 中为它创建一个字段,您还将 MainPage 类声明为一个静态字段,将其用作整个应用程序的“外壳”...... '很高兴:在 AppViewModel 中,您可以实现或引用所有其他命名空间。

此致


推荐阅读