我正在尝试在DataBinding
类型的ComboBox
中的可编辑myStrings
和设置Properties.Settings.Default
之间创建双向System.Collections.Specialized.StringCollection
。
在我的示例中,Properties.Settings.Default.myStrings
中的代码只被加载到ComboBox中一次。使用button_Click()
更新和保存设置(名为&#34的按钮;填充")不会更新ComboBox。我必须重新启动应用才能看到更改。
打字"梨"在ComboBox中并使用button_Click()
保存设置(按钮名为" fill2"),根本不做任何事情。
我想要实现的目标是:
Properties.Settings.Default.myStrings
的当前内容,即使设置已更新。Properties.Settings.Default.myStrings
应该更新并保存。MainWindow.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:comboBoxDataBinding"
xmlns:Properties="clr-namespace:comboBoxDataBinding.Properties" x:Class="comboBoxDataBinding.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="212" Width="318">
<Window.DataContext>
<Properties:Settings/>
</Window.DataContext>
<Window.Resources>
<local:MyStringsConverter x:Key="MyStringsConverter"/>
</Window.Resources>
<Grid>
<ComboBox x:Name="comboBox" Margin="10,10,10,10" VerticalAlignment="Top" IsEditable="True" ItemsSource="{Binding myStrings, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"/>
<Button x:Name="button" Content="fill" HorizontalAlignment="Left" Margin="21,86,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
<Button x:Name="button1" Content="fill2" HorizontalAlignment="Left" Margin="21,111,0,0" VerticalAlignment="Top" Width="75" Click="button1_Click"/>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace comboBoxDataBinding {
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e) {
System.Collections.Specialized.StringCollection sc = Properties.Settings.Default.myStrings;
sc.Add("Apple");
sc.Add("Orange");
Properties.Settings.Default.myStrings = sc;
Properties.Settings.Default.Save();
}
private void button1_Click(object sender, RoutedEventArgs e) {
Properties.Settings.Default.Save();
}
}
class MyStringsConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
return value;
}
}
}