Simple WPF RadioButton Binding?

后端 未结 8 1002
难免孤独
难免孤独 2020-12-12 16:00

What is the simplest way to bind a group of 3 radiobuttons to a property of type int for values 1, 2, or 3?

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 16:53

    Actually, using the converter like that breaks two-way binding, plus as I said above, you can't use that with enumerations either. The better way to do this is with a simple style against a ListBox, like this:

    Note: Contrary to what DrWPF.com stated in their example, do not put the ContentPresenter inside the RadioButton or else if you add an item with content such as a button or something else, you will not be able to set focus or interact with it. This technique solves that. Also, you need to handle the graying of the text as well as removing of margins on labels or else it will not render correctly. This style handles both for you as well.

    
    
    
        
    
        
        
    
        
    
        
            
                
                    
                
            
        
    
        
            
                
            
        
    
    
    
    
    

    You now have the look and feel of radio buttons, but you can do two-way binding, and you can use an enumeration. Here's how...

    
    
        Some option
        Some other option
        Yet another option
    
    
    

    Also, since we explicitly separated out the style that tragets the ListBoxItem rather than putting it inline, again as the other examples have shown, you can now create a new style off of it to customize things on a per-item basis such as spacing. (This will not work if you simply try to target ListBoxItem as the keyed style overrides generic control targets.)

    Here's an example of putting a margin of 6 above and below each item. (Note how you have to explicitly apply the style via the ItemContainerStyle property and not simply targeting ListBoxItem in the ListBox's resource section for the reason stated above.)

    
        
    
    
    
    
        Some option
        Some other option
        Ter another option
    
    
    

提交回复
热议问题