【问题标题】:Binding a separate data source within a bound datatemplate在绑定的数据模板中绑定单独的数据源
【发布时间】:2017-11-18 12:59:49
【问题描述】:

我在翻转视图中有以下简单的数据模板。

<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>

但我不知道如何将 Header 文本框绑定到 viewmodel 上的 generalcomment,因为 Generalcomment 不是跳蚤集合的一部分。如果有人知道如何做到这一点,将不胜感激。

谢谢

【问题讨论】:

    标签: c# xaml binding uwp


    【解决方案1】:

    您正在寻找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>
    

    这里有更多信息:RelativeSource on MSDN,本质上这是在说“找到我上方的UserControl 元素,并绑定到它的DataContext,这将是视图模型,然后是GeneralComment 属性";显然,如果您使用的不是 UserControl(例如 Page 等),则将其替换为该类型。


    UWP 决定要与众不同的地方。

    正如 GeorgeT 所指出的,AncestorType 在 UWP 中不受支持,因此有一种解决方法,如下所述:How to do relativesource mode find ancestor (or equivalent) in UWP

    我可能会这样做的方式是为用户控件设置一个名称,然后执行:

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

    【讨论】:

    • 谢谢,但这似乎不起作用,我认为这是因为 UWP 不支持祖先类型。
    • @GeorgeT 哦,好吧,这不是一场彻头彻尾的噩梦。 叹息我发现了其他可能有帮助的东西,我会更新我的答案。
    • 我实际上只是在看那个帖子,但你省去了我把它应用到这个问题上的麻烦。再次感谢,现在一切正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2011-04-30
    • 2014-08-23
    相关资源
    最近更新 更多