我有一个绑定到对象的文本块。双向绑定工作得很好,不出所料。
在代码隐藏中:
txtNumberOfPlayers.DataContext = tournament.ChipSet;在.xaml中:
<toolkit:NumericUpDown x:Name="txtNumberOfPlayers" Value="{Binding NumberOfPlayers, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />在Chipset类中,当NumberOfPlayers设置为(OnPropertyChanged("NumberOfPlayers");)时,我会发出更改通知
但是..。当我完全重新分配对象时,它不会更新UI,除非我再次调用datacontext赋值。例如,假设我加载了一个不同的芯片组对象。
Chipset newChipSet = LoadChipset();
tournament.ChipSet = newChipSet;这不会在进行分配时更新txtNumberOfPlayers。它只有在我这样做的时候才能起作用:
Chipset newChipSet = LoadChipset();
tournament.ChipSet = newChipSet;
//have to call this again which seems redundant
txtNumberOfPlayers.DataContext = tournament.ChipSet;所以我想,也许我必须将更改通知放在芯片组对象上,如下所示:
private Chipset chipset;
public Chipset ChipSet
{
get { return chipset; }
set
{
if (chipset != value)
{
chipset = value;
OnPropertyChanged("ChipSet");
}
}
}但这并不管用。
所以我的问题是-当我将一个新的对象分配给旧的对象而不重新绑定datacontext时,如何让UI更新。
谢谢!
发布于 2010-07-22 06:15:48
您应该为您的绑定指定RelativeSource:
Value={Binding NumberOfPlayers, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type YourNamespace:YourTypeContainingChipsetProperty}}}编辑
您的案例中的DependencyProperty示例。将YourCustomControl更改为控件的类名:
public static DependencyProperty ChipsetProperty =
DependencyProperty.Register("Chipset", typeof(Chipset),
typeof(YourCustomControl),
new FrameworkPropertyMetadata
(null,
FrameworkPropertyMetadataOptions
.
BindsTwoWayByDefault, ChipsetPropertyChangedCallback));
public Chipset Chipset
{
get { return (Chipset)GetValue(ChipsetProperty); }
set { SetValue(ChipsetProperty, value); }
}
private static void ChipsetPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var yourCustomControl = d as YourCustomControl;
if (yourCustomControl != null)
{
//your logic on property changed goes here; don't raise OnPropertyChanged!
}
}https://stackoverflow.com/questions/3304287
复制相似问题