[英]How to bind grid content to a UserControl
我有一個 Grid 並希望將用戶控件顯示為網格的子級或網格的內容。 單擊按鈕時,將根據情況顯示一些用戶控件。 請檢查 xaml 零件和后面的代碼。
<Grid x:Name="ContentPanel" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Margin="5,5,5,5">
</Grid>
我想將 Grid 內容綁定到下面的activeUserControl object。
public class MainVM
{
public UserControl activeUserControl;
Stability stability;
Tank tank;
public MainVM()
{
stability = new Stability();
tank = new Tank();
activeUserControl = stability;
stability.Visibility = Visibility.Visible;
}
}
問題是您不能直接綁定到Grid
的Children
集合,因為它不是DependencyProperty
。 您必須實現附加屬性或行為才能這樣做。 但是,您可以將ContentControl
放入Grid
或將其替換為一種解決方法。 然后將其Content
綁定到視圖 model 中的activeUserControl
屬性。 通常屬性以大寫字母開頭,所以我對其進行了調整。
<Grid x:Name="ContentPanel" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,5,5,5">
<ContentControl Content="{Binding ActiveUserControl}"/>
</Grid>
確保您的MainVM
在任何父控件中設置為DataContext
,否則此綁定將不起作用。 activeUserControl
必須是使其可綁定的屬性。 在MainVM
中實現INotifyPropertyChanged
,以便ContentControl
在屬性更改並調整其Content
時得到通知。
// Implement "INotifyPropertyChanged" so controls get notified about property changes
public class MainVM : INotifyPropertyChanged
{
// Backing field of the "ActiveUserControl" property
private UserControl _activeUserControl;
public UserControl ActiveUserControl
{
get => _activeUserControl;
set
{
// Only set the value if it has changed
if (_activeUserControl != value)
{
_activeUserControl = value;
// Signal to the control that it needs to update the value
OnPropertyChanged(nameof(ActiveUserControl));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MainVM()
{
// ...your code.
ActiveUserControl = stability;
// ...your code.
}
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
這應該可以解決您的問題,但您的代碼仍然是 MVVM 和代碼隱藏的混合體。 理想情況下,視圖 model 中不應有任何 UI 控件引用。
考慮使用INotifyPropertyChanged
和數據模板創建Tank
和Stability
視圖模型來顯示它們,而不是在視圖 model 中使用UserControl
。 在這種情況下,您仍然可以使用ContentControl
。
<ContentControl Content="{Binding activeUserControl}">
<ContentControl.Resources>
<DataTemplate DataType={x:Type TankViewModel}>
<!-- ...data template equivalent of your "Tank" user control. -->
</DataTemplate>
<DataTemplate DataType={x:Type StabilityViewModel}>
<!-- ...data template equivalent of your "Stability" user control. -->
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.