简体   繁体   English

在绑定的数据模板中绑定一个单独的数据源

[英]Binding a separate data source within a bound datatemplate

I have the following simple datatemplate within a flipview. 我在翻转视图中有以下简单的数据模板。

<FlipView x:Name="MyFlipview" ItemsSource="{x:Bind Path=ViewModel.Fleas}" >
       <FlipView.ItemTemplate>
            <DataTemplate  x:DataType="types:FleaType">     
               <TextBox x:Name ="Header" Text= "{Binding Path = ViewModel.GeneralComment}"></TextBox> 
               <TextBox x:Name ="FleaName" Text= "{Binding Path = FleaName}"></TextBox>

            </DataTemplate>
       </FlipView.ItemTemplate>
</FlipView>

But I dont know how to bind the Header textbox to generalcomment on the viewmodel as Generalcomment isnt part of the fleas collection. 但是我不知道如何将Header文本框绑定到viewmodel上的generalcomment上,因为Generalcomment不是跳蚤集合的一部分。 If anyone knows how to accomplish this it'd be much appreciated. 如果有人知道如何做到这一点,将不胜感激。

Thanks 谢谢

You're looking for RelativeSource : 您正在寻找RelativeSource

<FlipView x:Name="MyFlipview" ItemsSource="{x:Bind Path=ViewModel.Fleas}" >
       <FlipView.ItemTemplate>
            <DataTemplate  x:DataType="types:FleaType">     
               <TextBox x:Name ="Header" Text= "{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext.GeneralComment}"></TextBox> 
               <TextBox x:Name ="FleaName" Text= "{Binding Path = FleaName}"></TextBox>

            </DataTemplate>
       </FlipView.ItemTemplate>
</FlipView>

There's more info here: RelativeSource on MSDN , essentially what this is doing is saying "Find the UserControl element above me, and bind to its DataContext which will be the view model, and then the GeneralComment property"; 这里有更多信息: MSDN上的RelativeSource ,基本上是在说:“找到我上方的UserControl元素,并绑定到其DataContext (将成为视图模型,然后绑定到GeneralComment属性)”; obviously if you're using something other than UserControl (eg a Page etc) then replace it with that type. 显然,如果您使用的不是UserControl(例如Page等),则将其替换为该类型。


The One Where UWP Decides It Wants To Be Different. UWP决定与众不同的地方。

As GeorgeT has indicated, AncestorType isn't supported in UWP, as such there's a way around this as explained here: How to do relativesource mode find ancestor (or equivalent) in UWP 正如GeorgeT指出的那样,UWP不支持AncestorType ,因此有一种解决方法,如下所述: 如何在UWP中使用相对源模式查找祖先(或等效祖先)

The way I'd probably do it is to just set a name for the user control, and then do: 我可能会这样做的方法是只为用户控件设置一个名称,然后执行以下操作:

{Binding ElementName=MyUserControl, Path=DataContext.GeneralComment}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM