【发布时间】:2016-10-06 00:05:54
【问题描述】:
我有一个关于使用主从布局的 WPF 绑定的问题。
主视图包含一个带有 TreeListView 的 DevExpress GridControl。 当 TreeListView 选定项更改(通过绑定)时,详细视图内容会更新。 详细视图只包含一个 ContentControl,它的 Content 属性绑定到 TreeListView 的当前选定项。 为了以与所选项目的类型相对应的方式显示详细视图,将几个 DataTemplates 注册到当前应用程序资源。 在我的例子中,DataTemplates 只是一个用户控件。
当主视图TreeListView中的选择改变时,相应的DataTemplate被正确显示。
我的一个详细视图包含一个 DevExpress ListBoxEdit。 SelectedIndex 与 UpdateSourceTrigger=PropertyChanged 绑定。
我的问题是,当在主视图中选择另一个项目时,绑定属性的设置器被调用值为 -1。 似乎在卸载或处置或取消绑定控件时收到 -1 默认值。这搞砸了我的视图模型。
是否有适当的方法避免在控件卸载时在 ViewModel 中收到通知?
[更新] 包含详细视图的 ContentControl 定义如下:
<ContentControl Grid.Column="1" Content="{Binding CurrentApplicationSettings}" Margin="10,0,0,0"/>
在对应的视图模型中(SetValue方法调用OnPropertyChanged):
public IApplicationSettingsViewModel CurrentApplicationSettings
{
get { return GetValue<IApplicationSettingsViewModel>(); }
set { SetValue(value); }
}
在我遇到问题的详细视图中,ListBoxEdit 的定义如下:
<dxe:ListBoxEdit ShowBorder="False" ItemsSource="{Binding AllLoggingLevels, Mode=OneTime}" SelectedIndex="{Binding Path=LoggingLevel, Mode=TwoWay, Converter={StaticResource LogLevelConverter}, UpdateSourceTrigger=PropertyChanged}">
<dxe:ListBoxEdit.StyleSettings>
<dxe:RadioListBoxEditStyleSettings/>
</dxe:ListBoxEdit.StyleSettings>
</dxe:ListBoxEdit>
在对应的ViewModel中:
public LoggingLevel LoggingLevel
{
get { return GetValue<LoggingLevel>(); }
set { SetValue(value); }
}
DataTemplates 是通过代码注册的:
public void RegisterDataTemplate(DataTemplate dataTemplate)
{
object dataTemplateKey = dataTemplate.DataTemplateKey;
if (dataTemplateKey == null)
{
throw new InvalidOperationException("The data template has an invalid key");
}
System.Windows.Application.Current.Resources.Add(dataTemplateKey, dataTemplate);
}
非常感谢 菲利普
【问题讨论】:
-
我相信最少的代码将帮助我们帮助您。 stackoverflow.com/help/mcve
标签: wpf binding master-detail