【发布时间】:2016-09-20 06:15:18
【问题描述】:
我有一个用于控制 WCF-RESTful 服务的 WPF 应用程序,即用于启动、初始化和停止它。因此,我有一个 MainWindow UI,其中包含一个 UserControl 来配置设置。当我初始化我的服务时,一些数据被加载到DependencyProperties 和ObservableCollections 以在 GUI 中显示。这是我更新这些设置的方法的一部分:
public partial class MainWindow : Window {
private void InitializeService (bool reInitialize = false) {
var restService = (RestService)this.ServiceHost.SingletonInstance;
var settings = restService.GetSettings();
//UCSettings is the "x:name" of the embedded UserControl "UserControlSettings" in this window
this.UCSettings.ExecutionTimes.Clear();
settings.ExecutionTimes.ForEach(x => this.UCSettings.ExecutionTimes.Add(x));
this.UCSettings.TableConfigurationLoader = settings.Timer.Find(x => x.Name == "TableConfigLoader");
}
}
public partial class UserControlSettings : UserControl {
public ObservableCollection<ExecutionTime> ExecutionTimes { get; set; }
public static readonly DependencyProperty TableConfigurationLoaderProperty = DependencyProperty.Register("TableConfigurationLoader", typeof(Setting), typeof(UserControlSettings), new FrameworkPropertyMetadata(default(Setting)));
public Setting TableConfigurationLoader {
get { return (Setting)this.GetValue(TableConfigurationLoaderProperty); }
set { this.SetValue(TableConfigurationLoaderProperty, value); }
}
}
public class Setting {
public string Name { get; set; }
public bool IsEnabled { get; set; }
public int ExecutionTimeId { get; set; }
}
public class ExecutionTime {
public int Id { get; set; }
public string Value { get; set; }
}
在代码设计器 (UserControlSettings.xaml.cs) 中,这些属性用于 ComboBox 的某些绑定中:
<UserControl x:Class="InsightTool.Gui.UserControlSettings" x:Name="UCSettings">
<ComboBox x:Name="CbConfigLoadingExecutionTime" ItemsSource="{Binding ElementName=UCSettings, Path=ExecutionTimes}" DisplayMemberPath="Value" SelectedValue="{Binding ElementName=UCSettings, Path=TableConfigurationLoader.ExecutionTimeId}" SelectedValuePath="Id"/>
</UserControl>
当我第一次使用InitializeService 方法加载数据时,一切正常。 ComboBox 填充ObservableCollection 的数据,匹配值由ExecutionTimeId 自动选择。
当我尝试“重新初始化”服务时,我再次调用相同的方法,但 SelectedValue 绑定不再起作用。我在调试器中检查了这些属性的值,但在此方法中再次正确设置了它们。我在这里做错了什么?一些样本:
【问题讨论】:
-
你是否在没有提升 PropertyChanged 的情况下替换了 ObservableCollection?
-
@EdPlunkett 我只清除并重新填充此集合。通常它应该在发生更改时自动引发 PropertyChange,还是我错了?
-
但是 ItemsSource 绑定确实有效,即 ComboBox 有一个执行时间列表?这个新列表是否包含先前选择的值,即具有相同
Id的 ExecutionTime? -
在运行时使用 Snoop 检查您的 DataContext 和绑定
-
@Clemens 是的,你的两个建议都有。如果打开
ComboBox,项目仍然存在。好像只有自动选择失败了
标签: c# wpf xaml data-binding