我正在开发一个WPF应用程序,我想要的是,如果选择了组a中的特定单选按钮,程序会创建第二组单选按钮,称之为组B,同时创建一个禁用的文本框。现在我想创建一个事件,这样,如果用户从组B中选择选项3,文本框将变为启用状态,当未选择时,它将再次禁用。现在我有了编程工作,但当我试图创建事件处理程序时,我引用了一个不存在的控件,它不会构建。我正在尝试使用this.textBox.IsEnabled = true/false;
来启用/禁用文本框。所以,只是为了确保实际问题是清楚的。如何启用/禁用在生成/运行时不存在的文本框?
我的活动:
private void AllowRegion(object sender, RoutedEventArgs e)
{
this.SpecRegionText.IsEnabled = true;
}
private void DisallowRegion(object sender, RoutedEventArgs e)
{
this.SpecRegionText.IsEnabled = false;
}
创建控件:
private void AddSpecificControls()
{
Grid grid = (Grid)this.SpecsGrid;
RadioButton recruitmentEnabled = (RadioButton)this.RecruitmentEnabled;
if ((bool)recruitmentEnabled.IsChecked)
{
RadioButton newNations = new RadioButton();
newNations.Margin = new Thickness(10, 10, 0, 0);
newNations.HorizontalAlignment = HorizontalAlignment.Left;
newNations.Name = "NewNations";
newNations.GroupName = "RecruitType";
newNations.Content = "New Nations";
newNations.Width = 124;
grid.Children.Add(newNations);
RadioButton reFound = new RadioButton();
reFound.Margin = new Thickness(10, 30, 0, 0);
reFound.HorizontalAlignment = HorizontalAlignment.Left;
reFound.Name = "Refound";
reFound.GroupName = "RecruitType";
reFound.Content = "Refounded Nations";
reFound.Width = 124;
grid.Children.Add(reFound);
RadioButton specRegionRadio = new RadioButton();
specRegionRadio.Margin = new Thickness(10, 50, 0, 0);
specRegionRadio.HorizontalAlignment = HorizontalAlignment.Left;
specRegionRadio.VerticalAlignment = VerticalAlignment.Top;
specRegionRadio.Name = "SpecRegionRadio";
specRegionRadio.GroupName = "RecruitType";
specRegionRadio.Content = "Specific Region";
specRegionRadio.Width = 124;
specRegionRadio.Height = 23;
specRegionRadio.Checked += new RoutedEventHandler(AllowRegion);
specRegionRadio.Unchecked += new RoutedEventHandler(DisallowRegion);
grid.Children.Add(specRegionRadio);
TextBox specRegionText = new TextBox();
specRegionText.Margin = new Thickness(139, 50, 0, 0);
specRegionText.HorizontalAlignment = HorizontalAlignment.Left;
specRegionText.VerticalAlignment = VerticalAlignment.Top;
specRegionText.Name = "SpecRegionText";
specRegionText.Text = "Region";
specRegionText.Width = 120;
specRegionText.Height = 23;
specRegionText.IsEnabled = false;
grid.Children.Add(specRegionText);
}
}
您可以使用lambda内联挂钩委托,但为此,您必须在radioButton之前声明textBox。
TextBox specRegionText = new TextBox();
RadioButton specRegionRadio = new RadioButton();
specRegionRadio.Checked += (s,e) => specRegionText.IsEnabled = true;
specRegionRadio.Unchecked += (s,e) => specRegionText.IsEnabled = false;