2014-02-19 71 views
0

我正在设置要基于Radioboxes的选择启用组合框。目前它在下面的代码中产生这个错误Object reference not set to an instance of an object.。我一次只做一个,并使ComboBox False工作。当我将Disc_OnChecked设置为true时,它产生了错误。如果我能得到帮助绕过这个错误,请。单选按钮Isenabled麻烦

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> 

回答

1

让我来刺它。

当您的控件变得连线起来时,可能会发生这种情况,此时ComboBox尚未实例化。

您的处理程序中简单地检查空:

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; 
} 

干杯

+0

绝对完美谢谢! – Master

+0

如果它解决了您的问题,请不要忘记标记为答案。干杯。 –

0

您还可以在ComboBoxItem IsSelected属性绑定到单选财产器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>