【发布时间】:2015-05-25 23:08:49
【问题描述】:
我的应用结构如下:
MainPage.xaml 有一个 ListView,它的 ItemSource 设置为 CollectionViewSource,它在代码隐藏中填充:
MainPage.xaml
<Page.Resources>
...
<CollectionViewSource x:Key="src" IsSourceGrouped="True" />
...
</Page.Resources>
<Grid>
...
<ListView
ItemsSource="{Binding Source={StaticResource src}}"
SelectionMode="None"
ItemTemplate="{StaticResource processTemplate}"
ItemContainerStyle="{StaticResource ListViewItemStyle}">
<ListView.GroupStyle>
<GroupStyle HeaderTemplate="{StaticResource groupTemplate}"/>
</ListView.GroupStyle>
</ListView>
...
</Grid>
MainPage.xaml.cs
var cvs = (CollectionViewSource)Resources["src"];
cvs.Source = groups.ToList();
groups 是一个 Linq 查询,它按对象属性对对象进行分组
这一切都可以很好地在 ListView 中成功显示我的组对象。我有一个问题是在单个列表项的布局内。该模板如下所示,其中包含在另一个文件中定义的用户控件。
MainPage.xaml
<DataTemplate x:Name="processTemplate">
<Grid>
...
<TextBlock Text="{Binding Path=Process}" ... />
<TextBlock Text="{Binding Path=Description}" ... />
<TextBlock Text="{Binding Path=LastSuccess}" ... />
<Button Grid.Column="1" Grid.RowSpan="3"
Background="{Binding Path=Status,
Converter={StaticResource stbConverter}}" ... />
<local:MinutesOverlay ... Visibility="{Binding Path=Status,
Converter={StaticResource stoConverter}}"
Overdue="{Binding Path=MinutesWarning}"
Alert="{Binding Path=MinutesAlert}"/>
</Grid>
</DataTemplate>
MinutesOverlay.xaml
<Grid>
...
<TextBlock Text="{Binding Path=Overdue}" />
<TextBlock Text="{Binding Path=Alert}" />
...
</Grid>
MinutesOverlay.xaml.cs
public sealed partial class MinutesOverlay : UserControl
{
public MinutesOverlay()
{
this.InitializeComponent();
}
public static readonly DependencyProperty OverdueProperty = DependencyProperty.Register(
"Overdue", typeof(int), typeof(MinutesOverlay), new PropertyMetadata(0));
public static readonly DependencyProperty AlertProperty = DependencyProperty.Register(
"Alert", typeof(int), typeof(MinutesOverlay), new PropertyMetadata(0));
public int Overdue
{
get { return (int)GetValue(OverdueProperty); }
set { SetValue(OverdueProperty, value); }
}
public int Alert
{
get { return (int)GetValue(AlertProperty); }
set { SetValue(AlertProperty, value); }
}
}
我的绑定不起作用,我不知道如何让它们起作用。目前,MinutesOverlay 控件的可见性由一个绑定控制,只要我不设置 MinutesOverlay 的 Datacontext,该绑定就可以工作。如果我确实通过 this.Datacontext = this 进行设置,则绑定无效,并且覆盖始终可见(大部分时间应该折叠)。
如果我在 MainPage.xaml 中设置 Overdue 和 Alert 的值而不进行绑定,它可以正常工作。
【问题讨论】:
-
您是否尝试在用户控件上设置名称 (x:Name="userControl") 并将绑定更改为 Text="{Binding Path=Alert, ElementName=userControl}"?
-
成功了,你能解释一下为什么吗?另外,如果您将其添加为答案,我可以接受
-
将其添加为答案。 MSDN:“默认情况下,绑定继承由 DataContext 属性指定的数据上下文(如果已设置)。但是,ElementName 属性是您可以显式设置绑定源并覆盖继承的数据上下文的方法之一。” - msdn.microsoft.com/en-us/library/…
标签: c# xaml data-binding datacontext win-universal-app