Answered Radiobutton wpf ischecked data binding

  • Friday, May 04, 2012 4:14 PM
     
      Has Code

    I have a master-detail wpf application. The "master" is a datagrid , and "detail" is two radio buttons. Based on the row selection the radio buttons are checked in the "detail" section.

    I am binding my Radio button the following way using a inttoboolean converter. 

    xaml :

                                <StackPanel Margin="2"> 
                                        <RadioButton Margin="0,0,0,5" Content="In Detail" IsChecked="{Binding Path=itemselect.OutputType, Converter ={StaticResource radtointOTSB}, ConverterParameter= 0}"/> 
                                        <RadioButton Content="In Breif" IsChecked="{Binding Path=itemselect.OutputType, Converter ={StaticResource radtointOTSB}, ConverterParameter= 1}"/> 
                                    </StackPanel> 
    

    In View Model:

     public class radtointOTSB : IValueConverter 
    { 
         object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) 
        { 
            int OTint = Convert.ToInt32(value); 
            if (OTint == int.Parse(parameter.ToString())) 
                return true; 
            else 
                return false; 
        } 
     
         object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
         { 
             return parameter; 
         } 
    } 
    

    My implementation works well for the first few selections in datagrid. And all of a sudden , neither of my radio button is selected.

    I have no clue on why it happens, Can any one find out what goes wrong ?

    Thanks in advance.


All Replies

  • Friday, May 04, 2012 5:24 PM
     
     

    Hi,

    from the posted code (assuming your values are convertible without exception), neither of your radios will be selected if the bound value is anything except 0 or 1.

    For further advice you have to post mor code (esp: how do you connect master and detail) and maybe you can check "the first few selections": does that mean "a small number of" or "after a specific master item is selected". What happens when you go back to the first selected item after a 'failing' selection.

    Cheers
    Jürgen

  • Friday, May 11, 2012 6:40 AM
    Moderator
     
     

    Hi maran1987,

    Any updates?

    We need more detail information about your code, so that we can help you out.

    Thank you.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us

  • Friday, May 11, 2012 10:07 AM
     
      Has Code

    Hi all,

    Thanks for response. @ Rohr : My values is always going to be either 0 or 1 .

    I will provide more code to make it clear what I am doing.

    My Master View xaml:

        <Grid>
            <my:DataGrid AutoGenerateColumns="False" foundation:CommandBehavior.RoutedEventName="SelectionChanged" foundation:CommandBehavior.TheCommandToRun="{Binding Path= ListGCommand}" SelectedItem="{Binding SelectedG}"  ItemsSource="{Binding GameList}" SelectionMode="Single"  Margin="10,10,10,10" Name="dg1">
                <my:DataGrid.Columns>
                    <my:DataGridTextColumn Header="ID" Binding="{Binding ID}"></my:DataGridTextColumn>
                    <my:DataGridTextColumn Header="Name" Binding="{Binding Name}"></my:DataGridTextColumn>
                    <my:DataGridTextColumn Header="Description" Binding="{Binding Description}"></my:DataGridTextColumn>
                    <my:DataGridTextColumn Header="RadOption" Binding="{Binding SortType}"></my:DataGridTextColumn>
                </my:DataGrid.Columns>
            </my:DataGrid>
        </Grid>

    My Detail view xaml:

        <Grid>
            <StackPanel Margin="2">
                <StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
                    <Label Content="ID"></Label>
                    <TextBox Text="{Binding Path=Dispgames.ID}"/>
                </StackPanel>
                <RadioButton Margin="0,0,0,5" Content="Detailed Output" IsChecked="{Binding Path=Dispgames.SortType, Converter ={StaticResource radtointOTSB}, ConverterParameter= 0}"/>
                <RadioButton Content="Summary Output" IsChecked="{Binding Path =Dispgames.SortType,Converter ={StaticResource radtointOTSB}, ConverterParameter= 1}"/>
            </StackPanel>
        </Grid>

    My Master View Model:

      public class cselectvm: INotifyPropertyChanged
        {
            private TestonemanyEntities testcontxt = new TestonemanyEntities();
    
            public cselectvm()
            { 
                GameList = new ObservableCollection<Games> (from gam in testcontxt.Games 
                                                                select gam);
                listGCommand = new RelayCommand(() => SelectionGhaschanged());
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            public void OnPropertyChanged(PropertyChangedEventArgs e)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, e);
            }
    
            private ObservableCollection<Games> gameList;
            public ObservableCollection<Games> GameList
            {
                get { return gameList; }
                set { gameList = value; OnPropertyChanged(new PropertyChangedEventArgs("GameList")); }
            }
    
            private RelayCommand listGCommand;
            public ICommand ListGCommand
            {
                get { return listGCommand; }
            }
    
            private Games selectedG;
            public Games SelectedG
            {
                get { return selectedG; }
                set { selectedG = value; }
            }
    
            private void SelectionGhaschanged()
            {
                Messenger messenger = App.Messenger;
                messenger.NotifyColleagues("GSelectionChanged", selectedG);
                
            }
    
        }

    My Detail View Model:

    public class cdisplayvm: INotifyPropertyChanged { private TestonemanyEntities testcontxt = new TestonemanyEntities(); public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this, e); } public cdisplayvm() { Messenger messenger = App.Messenger; messenger.Register("GSelectionChanged", (Action<Games>)(param => trigprocess(param))); } private Games dispgames = new Games(); public Games Dispgames { get { return dispgames; } set { dispgames = value; OnPropertyChanged(new PropertyChangedEventArgs("Dispgames")); } } public void trigprocess(Games g) { if (g == null) { return; } Games dispgames = new Games(); Dispgames = g; } } public class radtointOTSB : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { int OTint = Convert.ToInt32(value); if (OTint == int.Parse(parameter.ToString())) return true; else return false; } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return parameter; } }

    Radio button states:

    ID 3 Radbtn1= 0 Radbtn2 = 1

    ID 5 Radbtn1 = 1 Radbtn2 = 0

    ID 3 Radbtn1 =0 Radbtn2 = 0 (err)

    ID 5 Radbtn1 =1 Radbtn2 = 0  

    Hope I improved my question :) . I have no clue on why it happens is this the right way to databind radiobuttons ?

    Regards.

  • Friday, May 11, 2012 12:59 PM
     
     

    Hi,

    as far as I can see, the code looks as if it should do what is intended.

    Just to make it a bit more simple and straightforward, you should remove the CommandBehavior and trigger the NotifyColleagues in the setter of SelectedG. By using the SelectedItem in the event, you mix up two possibly differing things. So, either use the SelectionChangedEventArgs with the event/CommandBehavior or trigger the NotifyColleagues in the setter of SeletedG.

    Have you done some debugging yet? What are the contents of "g" in the first line of "trigprocess" and of "value" in the Convert-method when the error is thrown? And again: Does always the third selection fail or does always the second selection of an arbitrary item fail and what kind of error is thrown?

    Cheers
    Jürgen

    NB: Furthermore the ConvertBack-method should return a numeric value (0 or 1) or - better - throw an exception as it should not be called anyway. The line "Games dispgames = new Games();" yields nothing (and hopefully is dismissed by the compilers optimization). But these points should not have any impact on the issue.

  • Saturday, May 12, 2012 1:28 PM
     
     

    It is better to bind it this way:

    <Grid>
           
    <StackPanel Margin="2" DataContext={Binding Dispgames}>
               
    <StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
                   
    <Label Content="ID"/>
                   
    <TextBox Text="{Binding Path=ID}"/>
               
    </StackPanel>
               
    <RadioButton Margin="0,0,0,5" Content="Detailed Output" IsChecked="{Binding SortType, Mode=TwoWay, Converter ={StaticResource radtointOTSB}, ConverterParameter= 0}"/>
               
    <RadioButton Content="Summary Output" IsChecked="{Binding SortType, Mode=TwoWay, Converter ={StaticResource radtointOTSB}, ConverterParameter= 1}"/>
           
    </StackPanel>
       
    </Grid>

    Also try to use GroupName property.

  • Saturday, May 12, 2012 5:10 PM
     
     

    Hi Xperiandri,

    can you please explain, why it would be better
    - to 'split' the BindigPath between the RadioButtons/TextBox and the StackPanel and 
    - to use TwoWay-Mode.

    As far as I understood, setting the value by checking the radios is not intended (so they are 'display-only').

    Which GroupName property are you refering to?

    Cheers
    Jürgen

  • Friday, May 18, 2012 2:14 PM
     
     Answered Has Code

    Hello,

    Thanks everyone .

    I found that the value false is not passed to the dependency property. This has been solved in .Net 4.0 . I am using .net 3.5 SP1 thats the reason. The only way was to have a custom radiobutton.I share here a custom radiobutton class i found.

        public class RadioButtonExtended : RadioButton
        {
            public static readonly DependencyProperty IsCheckedExtProperty =
                DependencyProperty.Register("IsCheckedExt", typeof(bool?), typeof(RadioButtonExtended),
                                            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsCheckedRealChanged));
    
            private static bool _isChanging;
    
            public RadioButtonExtended()
            {
                Checked += RadioButtonExtendedChecked;
                Unchecked += RadioButtonExtendedUnchecked;
            }
    
            public bool? IsCheckedExt
            {
                get { return (bool?)GetValue(IsCheckedExtProperty); }
                set { SetValue(IsCheckedExtProperty, value); }
            }
    
            public static void IsCheckedRealChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                _isChanging = true;
                ((RadioButtonExtended)d).IsChecked = (bool)e.NewValue;
                _isChanging = false;
            }
    
            private void RadioButtonExtendedChecked(object sender, RoutedEventArgs e)
            {
                if (!_isChanging)
                    IsCheckedExt = true;
            }
    
            private void RadioButtonExtendedUnchecked(object sender, RoutedEventArgs e)
            {
                if (!_isChanging)
                    IsCheckedExt = false;
            }
        } 

    • Marked As Answer by maran1987 Friday, May 18, 2012 2:14 PM
    •