C# 绑定到对象本身,不会';当单个属性更改时,不会更新
在列表框中,我有一个具有许多属性的对象列表,由于我一次渲染所有对象,并且对象是通用的,所以我绑定到对象本身C# 绑定到对象本身,不会';当单个属性更改时,不会更新,c#,.net,wpf,xaml,data-binding,C#,.net,Wpf,Xaml,Data Binding,在列表框中,我有一个具有许多属性的对象列表,由于我一次渲染所有对象,并且对象是通用的,所以我绑定到对象本身 <local:ItemRenderer ItemReference="{Binding Path=."}/> 然后我试着装订 <local:ItemRenderer ItemReference="{Binding Self"}/> 不更新对象。根据需要将控件或视图或页面的datacontext或全部重置为null,然后将其交换回最近更改的实例。将其更改为同一引用
<local:ItemRenderer ItemReference="{Binding Path=."}/>
然后我试着装订
<local:ItemRenderer ItemReference="{Binding Self"}/>
不更新对象。根据需要将控件或视图或页面的datacontext或全部重置为
null
,然后将其交换回最近更改的实例。将其更改为同一引用不起作用…需要两个步骤
下面是实际代码,我需要以相同的方式触发控件,因为在类似情况下,命令(从VM执行以保持VM和视图操作分离)更改为更新视图控件 下面的代码中也出现了同样的情况,即通知更改的单个属性没有更新整个实例绑定,如
CurrentBatch
上所示。必须更新其他控件,以表明有关CurrentBatch
的某些内容已更改
public MainWindow()
{
DataContext = VM = new CertifyingVM();
VM.CommandRefreshBindings = new OperationCommand(o =>
{
MainAccessionHeader.DataContext =
MainHeader.DataContext = null;
MainAccessionHeader.DataContext =
MainHeader.DataContext = VM;
var currentBatch = VM.CurrentBatch;
MainAccessionHeader.CurrentBatch = null;
MainAccessionHeader.CurrentBatch = currentBatch;
});
VM.LockBatchGui = new OperationCommand(o =>
{ ... }
OperationCommand
是我的ICommand
操作,在我的博客文章中演示了该操作
如何触发它取决于您,只需将datacontext的值删除为null,然后将其设置回原位。您可以使用
IMultiValueConverter
实现并绑定到对象本身和对象的任何属性更改时都会更改的属性:
public class TheConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values[0]; //return the actual object
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
XAML:
<local:ItemRenderer>
<local:ItemRendered.ItemsReference>
<MultiBinding>
<MultiBinding.Converter>
<local:TheConverter />
</MultiBinding.Converter>
<Binding Path="." />
<Binding Path="BindingNotifier" />
</MultiBinding>
</local:ItemRendered.ItemsReference>
</local:ItemRenderer>
这要求您在修改对象的任何属性时设置
BindingNotifier
属性。另一个选项是为每个属性添加
元素。这是一个非常有用的答案。我将不得不利用这一点和我的答案来为这个场景设计一个混合操作。
public class TheConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values[0]; //return the actual object
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
<local:ItemRenderer>
<local:ItemRendered.ItemsReference>
<MultiBinding>
<MultiBinding.Converter>
<local:TheConverter />
</MultiBinding.Converter>
<Binding Path="." />
<Binding Path="BindingNotifier" />
</MultiBinding>
</local:ItemRendered.ItemsReference>
</local:ItemRenderer>