里面有两个RadioButton
s和两个Label
s .xaml
,勾选一个RadioButton
使对应的Label
Enable。RadioButton1
被检查。运行app,Checked Event
会自动调用,但是Label为null,所以app报异常。
我只是使用一个变量来标记窗口是否是第一次创建的。是否还有其他方法?我不知道为什么应用程序在初始化所有组件后运行事件,谁能告诉我?
主窗口.xaml
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
<StackPanel>
<RadioButton
GroupName="Group"
IsChecked="True"
Content="RadioButton1"
x:Name="RadioButton1"
Checked="RadioButton1_Checked"
Unchecked="RadioButton1_Unchecked"/>
<RadioButton
GroupName="Group"
Content="RadioButton2"
x:Name="RadioButton2"
Checked="RadioButton2_Checked"
Unchecked="RadioButton2_Unchecked"/>
<Label
x:Name="Label1"
Content="Label1"/>
<Label
IsEnabled="False"
x:Name="Label2"
Content="Label2"/>
</StackPanel>
</Window>
主窗口.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication7
{
/// <summary>
/// MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private bool isFirstRun;
public MainWindow()
{
isFirstRun = true;
InitializeComponent();
isFirstRun = false;
}
private void RadioButton1_Checked(object sender, RoutedEventArgs e)
{
if (isFirstRun)
return;
Label1.IsEnabled = true;
}
private void RadioButton2_Checked(object sender, RoutedEventArgs e)
{
Label1.IsEnabled = false;
}
private void RadioButton1_Unchecked(object sender, RoutedEventArgs e)
{
Label2.IsEnabled = true;
}
private void RadioButton2_Unchecked(object sender, RoutedEventArgs e)
{
Label2.IsEnabled = false;
}
}
}