[英]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.