我有动态列表框包含文本框以显示列表项,因此我可以编辑列表框项。我的应用程序设置文件包含我要为该列表框绑定的字符串集合。我还想在列表框项的每次更改时更新设置文件,我创建了实现INotifyProprtyChanged的类。我已将字符串集合从设置文件转换为具有字符串属性的自定义类型的可观察集合。我将文本框绑定到该自定义类的属性,并在属性更改时更新源属性。我也想更新可观察的集合。并且还会更新我的应用设置文件。请帮帮我。任何帮助将非常感激。我的代码:
public class WindowViewModel : INotifyPropertyChanged
{
private ObservableCollection<UrlModel> customcollection;
public ObservableCollection<UrlModel> CustomCollection
{
get { return customcollection; }
set
{
customcollection = value;
NotifyPropertyChanged("CustomCollection");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
public WindowViewModel()
{
List<string> customlist = Properties.Settings.Default.CustomList.Cast<string>().ToList();
List<UrlModel> urllist = new List<UrlModel>();
urllist = customlist.Select(item => new UrlModel() { urlString = item }).ToList();
CustomCollection = new ObservableCollection<UrlModel>(urllist);
}
}
public class UrlModel : INotifyPropertyChanged
{
private string url;
public string urlString
{
get { return url; }
set
{
url = value;
NotifyPropertyChanged("urlString");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ViewModel = new WindowViewModel();
ListTwo.ItemsSource = ViewModel.CustomCollection;
}
private WindowViewModel viewModel;
public WindowViewModel ViewModel
{
get { return viewModel; }
set{
viewModel = value;
DataContext = value;
}
}
}
}
答案 0 :(得分:0)
在插入ObservableCollection
public WindowViewModel()
{
List<string> customlist = Properties.Settings.Default.CustomList.Cast<string>().ToList();
List<UrlModel> urllist = new List<UrlModel>();
urllist = customlist.Select(item => new UrlModel() { urlString = item }).ToList();
CustomCollection = new ObservableCollection<UrlModel>(urllist);
foreach(var model in CustomCollection)
{
model.PropertyChaged += SettingsUpdater; //Settings update fucntion
}
}
SettingsUpdater
的简单实现只会在其中一个更改时更新整个网址列表。
答案 1 :(得分:0)
我相信您正在使用数据模板来使列表框可编辑。如果是这种情况,在绑定文本时,在Xaml代码中包含Text =“{Binding urlString,UpdateSourceTrigger = PropertyChanged}”。
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Name="EditableText" Text="{Binding urlString,UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ListBox.ItemTemplate>