且构网

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

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

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

因为您没有添加字符串,但是将ComboBoxItems添加到ComboBox,则还必须设置其 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}"