[英]Binding Xaml UserControl view to it's code behind, but code behind bound to other object
我有一个由 Xaml 定义的 UserControl 和后面的代码。 它应该随着它所基于的 model 的变化而更新。
我在代码中构建了这些控件的每个实例,并设置了与一些 object _interestingSystem
的绑定。
var newViewInstance = new BroadcastCell
{
HeartbeatStatus = Heartbeat.Status.NotRx,
BindingContext = _interestingSystem,
};
broadcastCell.SetBinding(BroadcastCell.HeartbeatProperty, "HeartbeatStatus");
StatkStack.Children.Add(broadcastCell);
这些绑定有效,我可以看到响应 model 更改的代码隐藏很好。
现在我想在稍作修改和调整后将我的视图绑定到代码隐藏。
XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="56" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="65" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Title, FallbackValue=TestTitle, Mode=OneWay}" Grid.Column="1" />
<Label Text="{Binding SecondaryLine, FallbackValue=Test2nd}" Grid.Column="1" Grid.Row="1" />
</Grid>
代码隐藏
public Heartbeat.Status CurrentStatus;
static void OnHeartbeatStatusChanged(BindableObject sender, object oldValue, object newValue)
{
var thisInstance = (BroadcastCell)sender;
var newStatus = (Heartbeat.Status)newValue;
thisInstance.CurrentStatus= newStatus;
}
private void UpdateAndModifyResult()
{
SecondaryLine = $"{DateTime.Now} {CurrentStatus} @ {AnotherStatus}";
}
public String SecondaryLine
{
get { return _secondaryLine; }
set
{
_secondaryLine = value;
OnPropertyChanged();
}
}
我可以尝试将 Xaml 的绑定设置为代码隐藏,并将后面的代码设置为另一个 object 吗?
或者我是否需要将 xaml 属性名称硬编码到代码隐藏中以“手动”更新它们?
在 XAML 中,您可以使用FindAncestor
绑定模式将Binding
的源设置为根BroadcastCell
,如下所示:
<Label Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:BroadcastCell}}, Path=SecondaryLine}" Grid.Column="1" Grid.Row="1"/>
加载 XAML 时,绑定引擎将查找第一个BroadcastCell
object 的可视化树并绑定到其SecondaryLine
属性。
或者,您可以直接将您的视图绑定到您的 model 而无需通过执行以下操作在您的代码隐藏中手动设置任何类型的绑定:
<Label Text="{Binding Heartbeat.Status}" Grid.Column="1" Grid.Row="1"/>
前提是您将视图的DataContext
设置为正确的源 object。 您的代码隐藏将变为:
broadcastCell.DataContext = _interestingSystem;
这比在代码隐藏中定义绑定更合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.