2014-02-19 72 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>