Binding WPF combobox to a user settings property

前端 未结 2 1292
攒了一身酷
攒了一身酷 2021-01-23 14:20

I\'ve a combobox in WPF with 4 static values in it:



        
相关标签:
2条回答
  • 2021-01-23 14:54

    Since you don't add strings, but ComboBoxItems to your ComboBox, you would also have to set its SelectedValuePath property:

    <ComboBox SelectedValuePath="Content"
              SelectedValue="{Binding Source={x:Static properties:Settings.Default},
                                      Path=KeyModifier, Mode=TwoWay}">
        <ComboBoxItem>Alt</ComboBoxItem>
        <ComboBoxItem>Shift</ComboBoxItem>
        <ComboBoxItem>Ctrl</ComboBoxItem>
        <ComboBoxItem>Win</ComboBoxItem>
    </ComboBox>
    

    Alternatively add strings to the ComboBox, and use SelectedItem instead of SelectedValue:

    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    ...
    <ComboBox SelectedItem="{Binding Source={x:Static properties:Settings.Default},
                                     Path=KeyModifier, Mode=TwoWay}">
        <sys:String>Alt</sys:String>
        <sys:String>Shift</sys:String>
        <sys:String>Ctrl</sys:String>
        <sys:String>Win</sys:String>
    </ComboBox>
    

    Note also that since WPF 4.5 you may write the Binding like this:

    SelectedItem="{Binding Path=(properties:Settings.Default).KeyModifier, Mode=TwoWay}"
    
    0 讨论(0)
  • 2021-01-23 14:57

    Have you saved the settings after you change the values? Settings.Default.Save()

    0 讨论(0)
提交回复
热议问题