将 WPF 组合框绑定到用户设置属性 [英] Binding WPF combobox to a user settings property
问题描述
我在 WPF 中有一个组合框,其中有 4 个静态值:
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>
我想将此组合框的选定值与用户设置中的一个简单字符串属性连接起来.这工作半途而废:选定的值完美地写入 Settings.Default.KeyModifier ......但在重新启动应用程序后,组合框的选定值未设置......尽管所有其他控件(编辑、复选框)绑定相同其他属性的方式设置正确.
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?
推荐答案
由于您没有向 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}"
这篇关于将 WPF 组合框绑定到用户设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!