Binding WPF combobox to a user settings property

允我心安 提交于 2019-12-20 05:23:33

问题


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

<ComboBox 
      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>

I want to connect the selected value of this combobox with a simple string property in the user settings. That works half way: The selected value is perfectly written to Settings.Default.KeyModifier ... But after restarting the application the selected value of the combobox is not set ... despite that all other controls (Edits, Checkboxes) binded the same way on other properties are set correctly.

Is there some mystery on filling a combobox with values from a binded property?

Or do I have to do the whole selection process on startup manually in code behind?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/43807345/binding-wpf-combobox-to-a-user-settings-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!