RadioButton
中有两个Label
和两个.xaml
,并选中一个RadioButton
使相应的Label
启用。 RadioButton1
已经过检查。运行应用程序,并自动调用Checked Event
,但Label为null,因此应用程序报告异常。
我只是使用变量来标记是否首次创建窗口。是否有其他方法?我不知道为什么应用程序在初始化所有组件之后运行事件,谁可以告诉我?
MainWindow.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>
MainWindow.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;
}
}
}
答案 0 :(得分:2)
我不确定您是否具有EventHandlers
的具体原因,但如果不是,您可以使用Xaml
绑定直接在ElementName
中执行此逻辑
示例:
<StackPanel>
<RadioButton x:Name="RadioButton1"
GroupName="Group"
IsChecked="True"
Content="RadioButton1" />
<RadioButton x:Name="RadioButton2"
GroupName="Group"
Content="RadioButton2" />
<Label x:Name="Label1"
IsEnabled="{Binding IsChecked, ElementName=RadioButton1}"
Content="Label1"/>
<Label x:Name="Label2"
IsEnabled="{Binding IsChecked, ElementName=RadioButton2}"
Content="Label2"/>
</StackPanel>
答案 1 :(得分:0)
为什么不简单地从XAML中移除Ischecked="True"
并将isFirstRun = false
之后设置的InitializeComponent();
变量替换为RadioButton1.IsChecked = true
这样您就可以节省定义isFirstRun
变量。