我无法访问我的 xaml 文件的设计视图,我必须对其进行编程,但我不知道如何进行
我尝试在网上搜索它,但是当我尝试所解释的内容时,它从未起作用。有没有办法以编程方式单击 WPF 按钮?
“我无法访问我的 xaml 文件的设计视图”您的 xaml 文件应该是您的 .cs 代码后面的视图文件。导航到解决方案资源管理器,您可以在其中找到解决方案的文件集合。如果解决方案资源管理器不存在,请使用
CTRL + ALT + L
,然后导航到您的视图文件。
要回答您的基本问题,如何纯粹从代码隐藏中编写按钮?请阅读文档此处:
// The click event handler for the existing button 'ButtonCreatedByXaml'.
private void ButtonCreatedByXaml_Click(object sender, RoutedEventArgs e)
{
// Create a new button.
Button ButtonCreatedByCode = new();
// Specify button properties.
ButtonCreatedByCode.Name = "ButtonCreatedByCode";
ButtonCreatedByCode.Content = "New button and event handler created in code";
ButtonCreatedByCode.Background = Brushes.Yellow;
// Add the new button to the StackPanel.
StackPanel1.Children.Add(ButtonCreatedByCode);
// Assign an event handler to the new button using the '+=' operator.
ButtonCreatedByCode.Click += new RoutedEventHandler(ButtonCreatedByCode_Click);
// Assign an event handler to the new button using the AddHandler method.
// AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ButtonCreatedByCode_Click);
// Assign an event handler to the StackPanel using the AddHandler method.
StackPanel1.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ButtonCreatedByCode_Click));
}
// The Click event handler for the new button 'ButtonCreatedByCode'.
private void ButtonCreatedByCode_Click(object sender, RoutedEventArgs e)
{
string sourceName = ((FrameworkElement)e.Source).Name;
string senderName = ((FrameworkElement)sender).Name;
Debug.WriteLine($"Routed event handler attached to {senderName}, " +
$"triggered by the Click routed event raised by {sourceName}.");
}