我遗漏了一些应该是直接绑定的东西,我希望有人能指出我正确的方向。
我有一个 SL 应用程序,它有一个名为 PeopleView 模型的视图模型,其中包含一个人的数字或属性(姓名地址等)该页面由一个用户控件、一个文本框和一个网格视图组成
用户控制代码
<frm:LabelFieldContainer Width="145"
Height="42"
Margin="12,12,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
MyContent="{Binding FirstName}"
MyLabel="{StaticResource lblFirstName}" />
<frm:LabelFieldContainer Width="178"
Height="42"
Margin="166,12,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
MyContent="{Binding LastName}"
MyLabel="{StaticResource lblLastName}" />
</Grid>
这个容器由另一个用户控件组成,该控件绑定到资源字典以提取标签名称,然后是一个内容字段,该字段将绑定到从我的视图模型(MyContent)返回的属性。这里的目标是创建一个通用控件,用于显示集合中的标签名称和值。IE。名字:John 目前,该标签在绑定到资源字典时起作用,但值 (MyContent) 的绑定不返回任何内容。
这是 MainPage.xaml 的 xaml
<Grid x:Name="LayoutRoot" Background="White">
<uc:AddressContainer />
<TextBlock Width="200"
Height="50"
Margin="101,71,99,179"
FontSize="12"
Foreground="Black"
Text="{Binding LastName}" />
<telerik:RadGridView Name="GridView1" Margin="0,140,0,6"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AutoGenerateColumns="True"
IsFilteringAllowed="True">
</telerik:RadGridView>
mainpage.xaml 背后的代码是
public partial class MainPage : UserControl
{
//binding of view model to user control
public PeopleViewModel PeopleView
{
get { return (PeopleViewModel)GetValue(PeopleViewProperty); }
set { SetValue(PeopleViewProperty, value); }
}
// Using a DependencyProperty as the backing store for PeopleView. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PeopleViewProperty =
DependencyProperty.Register("PeopleView", typeof(PeopleViewModel), typeof(MainPage), new PropertyMetadata(new PeopleViewModel()));
public MainPage()
{
InitializeComponent();
this.LayoutRoot.DataContext = PeopleView.AllPeople; //tried this but no luck
this.GridView1.ItemsSource = PeopleView.AllPeople; //bound to a grid view for testing returns
}
我插入了一个网格只是为了测试,它返回的值很好。但是,我尝试将主视图的 DataContext 绑定到集合,以便我可以在用户控件或我在主页中添加的测试文本块中填充绑定字段。
有人可以为我指出正确的方向,了解如何将 UIElements 正确绑定到 ItemsSource 之外的集合。我一直对网格或列表框项目执行此操作没有问题,但现在在尝试表示某些内容(UI 中的单个字段)时我遇到了困难。 更新:
经过短暂的心理失误后,我重新绑定了一个集合,我会将用户控件放入列表框中,这是更新后的主页 xaml
<Grid x:Name="LayoutRoot" Background="White">
<ListBox ItemsSource="{Binding}" Margin="0,0,0,166">
<ListBox.ItemTemplate>
<DataTemplate>
<uc:AddressContainer />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<telerik:RadGridView Name="GridView1" Margin="0,140,0,6"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AutoGenerateColumns="True"
IsFilteringAllowed="True">
</telerik:RadGridView>
我将 mainpage.xaml.cs 文件中的数据上下文更新为
public MainPage()
{
InitializeComponent();
this.DataContext = PeopleView.AllPeople; //updated here
}
我在列表框中得到了准确的记录 (2) 返回,但是绑定仍然没有在用户控件(内容字段)中发生以显示集合中返回的值
任何指针仍将不胜感激。