且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 WPF 组合框绑定到用户设置属性

更新时间:2022-06-22 02:41:27

由于您没有向 ComboBox 添加字符串,而是添加 ComboBoxItems,因此您还必须设置其 SelectedValuePath 属性:>

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>

或者将字符串添加到 ComboBox,并使用 SelectedItem 而不是 SelectedValue:

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>

还要注意,从 WPF 4.5 开始,您可以像这样编写绑定:


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

SelectedItem="{Binding Path=(properties:Settings.Default).KeyModifier, Mode=TwoWay}"