单选按钮Isenabled麻烦

时间:2014-02-19 21:44:08

标签: c# xaml

我根据Radiobox的选择设置了一个组合框。目前,它正在为以下代码生成此错误Object reference not set to an instance of an object.。我一次做了一个,并使ComboBox False工作。当我将Disc_OnChecked实现为设置为true时,它产生了错误。如果我能得到帮助,请绕过这个错误。

private void Cont_OnChecked(object sender, RoutedEventArgs e)
{
    Cf.IsEnabled = false;

}

private void Disc_OnChecked(object sender, RoutedEventArgs e)
{
    Cf.IsEnabled = true;
}

Xaml代码:

<GroupBox>
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Type:     "></TextBlock>
        <RadioButton Checked="Disc_OnChecked" GroupName="Group1" x:Name="Disc" IsChecked="true"  Content="Discrete" ></RadioButton>
        <RadioButton Checked="Cont_OnChecked" GroupName="Group1" x:Name="Cont" Content="Continuous"></RadioButton>
    </StackPanel>
</GroupBox>

<ComboBox x:Name="Cf" Width="125" SelectedIndex="1">
    <ComboBoxItem Content="Annual"></ComboBoxItem>
    <ComboBoxItem Content="Semi-annual"></ComboBoxItem>
</ComboBox>

2 个答案:

答案 0 :(得分:1)

让我试一试。

当你的控件连线时,这可能很糟糕,此时ComboBox还没有被实例化。

只需在处理程序中检查null:

private void Cont_OnChecked(object sender, RoutedEventArgs e)
{
    if (Cf != null)
       Cf.IsEnabled = false;

}

private void Disc_OnChecked(object sender, RoutedEventArgs e)
{
    if (Cf != null)
       Cf.IsEnabled = true;
}

干杯

答案 1 :(得分:0)

您还可以将ComboBoxItem IsSelected属性绑定到RadioButton IsChecked属性

<StackPanel>
  <RadioButton x:Name="rbtnA" Content="A"/>
  <RadioButton x:Name="rbtnB" Content="B"/>
  <RadioButton x:Name="rbtnC" Content="C"/>
  <ComboBox>
      <ComboBoxItem Content="ComboBoxItem A" IsSelected="{Binding ElementName=rbtnA,Path=IsChecked}"/>
      <ComboBoxItem Content="ComboBoxItem B" IsSelected="{Binding ElementName=rbtnB,Path=IsChecked}"/>
      <ComboBoxItem Content="ComboBoxItem C" IsSelected="{Binding ElementName=rbtnC,Path=IsChecked}"/>
  </ComboBox>
</StackPanel>