将WPF组合框绑定到用户设置属性 [英] Binding WPF combobox to a user settings property

查看:75
本文介绍了将WPF组合框绑定到用户设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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?

推荐答案

因为您没有添加字符串,但是将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}"

这篇关于将WPF组合框绑定到用户设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆