c# - 如何将网格内容绑定到 UserControl
问题描述
我有一个 Grid 并希望将用户控件显示为网格的子级或网格的内容。单击按钮时,将根据情况显示一些用户控件。请检查 xaml 部分和后面的代码。
<Grid x:Name="ContentPanel" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Margin="5,5,5,5">
</Grid>
我想将 Grid 内容绑定到下面的activeUserControl对象。
public class MainVM
{
public UserControl activeUserControl;
Stability stability;
Tank tank;
public MainVM()
{
stability = new Stability();
tank = new Tank();
activeUserControl = stability;
stability.Visibility = Visibility.Visible;
}
}
解决方案
问题是您不能直接绑定到Children
a 的集合Grid
,因为它不是 a DependencyProperty
。您必须实现附加属性或行为才能这样做。但是,您可以将 aContentControl
放入您的Grid
或替换它作为解决方法。然后将其绑定Content
到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
必须是使其可绑定的属性。INotifyPropertyChanged
在您的中实现MainVM
,以便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 和代码隐藏的混合体。理想情况下,视图模型中不应有任何 UI 控件引用。
考虑使用数据模板创建Tank
和Stability
查看模型来显示它们,而不是INotifyPropertyChanged
在你的视图模型中。在这种情况下,您仍然可以使用。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>
推荐阅读
- wordpress - 在 Wordpress 上更改滚动页面的背景颜色
- delphi - 在 Delphi (VCL/Windows) 中更改之前清除 TBitmap
- c# - 具有多种身份验证方案的 .NET Core API 测试
- c# - 难以理解的警告
- pdf - 创建旋转的地理空间 PDF
- python-3.x - UnicodeDecodeError:“charmap”编解码器无法解码位置 805 中的字节 0x81:字符映射到
- python - 数据框迭代不会增加变量
- java - 修复 Jackson 无法构造 Java.time.LocalDate 的实例
- html - 如何突出显示div中的搜索文本
- php - 转义包含 < 和 > 的 HTML 属性