【发布时间】:2018-06-07 03:43:30
【问题描述】:
我在 Visual Studio 中创建了一个新的 WPF 应用,并使用拖放编辑器放置了一个按钮,但我无法使用 .cs 文件访问该按钮
MainButton.Content = "Set output to red";
但我得到一个错误
System.NullReferenceException: '对象引用未设置为对象的实例。'
运行应用程序时 MainButton 为空。
拖放编辑器生成了这个 xaml 文件
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Black" BorderThickness="3">
<TextBlock x:Name="Output" Background="Transparent" TextAlignment="Center" TextWrapping="Wrap" Text="Output" Height="88" Width="264"/>
</Border>
<RadioButton x:Name="Option1" Content="Red Pill" HorizontalAlignment="Left" Margin="135,75,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked" IsChecked="True"/>
<RadioButton x:Name="Option2" Content="Blue Pill" HorizontalAlignment="Left" Margin="536,72,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked_1"/>
<Button x:Name="MainButton" Content="Set output to red" HorizontalAlignment="Left" Margin="279,100,0,0" VerticalAlignment="Top" Width="213" Height="41" Click="MainButton_Click"/>
</Grid>
</Window>
这是 .cs 文件
using System.Windows;
using System.Windows.Media;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainButton_Click(object sender, RoutedEventArgs e)
{
if ((bool)Option1.IsChecked)
{
Output.Background = Brushes.Crimson;
}
else
{
Option2.IsChecked = true;
Output.Background = Brushes.DodgerBlue;
}
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to blue";
}
}
}
我可以访问 UI 中的其他内容,例如单选按钮和文本块,但不能访问按钮。为什么会发生这种情况?
【问题讨论】:
-
我们可以看看一些 CS 吗?仅仅考虑a minimal, complete, verifiable example 还不够。我确定这只是一个初始化问题,或者它被用在了一个陌生的地方。
-
@JamesWhyte 这是一个非常小的应用程序,我是 c#/.net/visual studio 的新手,所以我只是添加了所有代码。希望这有助于澄清。
-
也许您要查找的变量是
Text而不是Content。尝试在 XAML 和 CS 中更改它。 -
当我编辑 xaml 文件时,它显示
The property 'Text' was not found in type 'Button'.c# 代码中的按钮类是 c# 中的 System.Windows.Control.Button,它没有该属性。 -
我明白了。我会做一个项目并开始修补。稳坐。 :)
标签: c# visual-studio xaml