【发布时间】:2017-11-27 11:38:51
【问题描述】:
我有一个 GridView,其中有一个包含自定义控件的 ItemTemplate:
<GridView
ItemsSource="{Binding Ubicaciones.Ubicaciones}">
<GridView.ItemTemplate>
<DataTemplate>
<ctr:HabitacionControl
Width="70"
Height="140"
Ubicacion="{Binding}"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
这是我的自定义用户控件:
<UserControl
x:Class="MySln.Mucama.Controls.HabitacionControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MySln.Mucama.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="200"
d:DesignWidth="97">
<UserControl.DataContext>
<local:HabitacionControlVM/>
</UserControl.DataContext>
<Grid>
<RelativePanel>
<Image x:Name="Puerta" Source="ms-appx:///Assets/Puerta.jpg"
Grid.RowSpan="5"/>
<TextBlock Text="{Binding Ubicacion.StrNombreMesa,FallbackValue=####}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Foreground="AliceBlue"
FontWeight="ExtraBold"
RelativePanel.AlignHorizontalCenterWithPanel="True"/>
</RelativePanel>
</Grid>
</UserControl>
及其背后的代码:
public sealed partial class HabitacionControl : UserControl
{
public HabitacionControl()
{
this.InitializeComponent();
}
public MyClass Ubicacion
{
get { return (MyClass)GetValue(UbicacionProperty); }
set { SetValue(UbicacionProperty, value); }
}
// Using a DependencyProperty as the backing store for Ubicacion. This enables animation, styling, binding, etc...
public static readonly DependencyProperty UbicacionProperty =
DependencyProperty.Register("Ubicacion", typeof(MyClass), typeof(HabitacionControl), new PropertyMetadata(new PropertyChangedCallback(OnUbicacionChanged)));
private static void OnUbicacionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//...
}
}
现在我需要将每个 Ubicaciones.Ubicaciones 绑定到我的 Customcontrol 的 Ubicación 属性。
在运行时,我的 gridview 会生成我的所有项目,但永远不会绑定到它的 Ubicacion 属性。
输出窗口中没有任何警告。
我错过了什么?还是做错了?
【问题讨论】:
-
从不明确设置 UserControl 的 DataContext,不管他们在在线教程或博客文章中告诉你什么。
-
@Clemens 不同意关闭。这个问题的 UserControlViewModel 和伪 DataContext 将其区分开来。这也是一个很好的、清晰的例子,我可以为做同样事情的人参考。我会欺骗关闭
DataContext = this;问题到你的例子:) -
将 UserControl 的 DataContext 设置为本地视图模型还是设置其本身并不重要。重要的事实是,这样做可以防止控件从其父控件继承 DataContext。因此,请参阅Binding to custom control inside DataTemplate for ItemsControl,了解如何在 UserControl 的 XAML 中编写 Bindngs。
标签: c# xaml uwp win-universal-app