XAML 如何从数据模板中绑定到页面上的属性(WinUI3)?

zf2sa74q  于 2023-08-01  发布在  其他
关注(0)|答案(2)|浏览(177)

我试图从DataTemplate中绑定到页面的属性。根据Databinding in Depth文章,每个数据绑定都有一个DataContext。这个DataContext默认为Page本身,并由子元素继承。但是,DataTemplate会覆盖这个DataContext,从而更改该数据模板 * 中所有元素 * 的上下文。
如何从该数据模板 * 中绑定到Page本身 * 上的属性?在下面的示例(已注解)中,我希望将TextBlock Text属性绑定到MyPage.MyName页面上的属性,该属性位于ListViewDataTemplate中。
使用x:Bind是否可以这样做,或者我是否需要使用Binding?我该怎么做?
MyPage.xaml.cs:

  1. public sealed partial class MyPage : Page
  2. {
  3. // ...
  4. public string MyName { get; set; }
  5. // MyCar is a class with a Name and Color property (both strings).
  6. public ObservableCollection<MyCar> Cars { get; set; }
  7. // ...
  8. }

字符串
MyPage.xaml:

  1. <StackPanel>
  2. <!-- The DataContext for the binding here is the Page itself (MyPage). -->
  3. <TextBlock x:Name="MyNameTextBlock"
  4. Text="{x:Bind MyName}"></TextBlock>
  5. <!-- The DataContext for the binding to the ItemsSource is also the Page itself (MyPage) -->
  6. <ListView x:Name="MyCarsListView"
  7. ItemsSource="{x:Bind Cars}">
  8. <ListView.ItemTemplate>
  9. <!-- The DataTemplate changes the DataContext, overriding the default. -->
  10. <!-- The new data context is now the specific item in the collection from the ItemsSource property in the ListView. -->
  11. <DataTemplate x:DataType="models:MyCar">
  12. <StackPanel>
  13. <!-- The DataContext for these two bindings is now the specific Car. -->
  14. <TextBlock x:Name="CarNameTextBlock"
  15. Text="{x:Bind Name}"></TextBlock>
  16. <TextBlock x:Name="CarColorTextBlock"
  17. Text="{x:Bind Color}"></TextBlock>
  18. <!-- This DOES NOT WORK. I want to refer to the MyName property on MyPage (a different DataContext). -->
  19. <TextBlock x:Name="OwnerTextBlock"
  20. Text="{x:Bind MyName}"></TextBlock>
  21. </StackPanel>
  22. </DataTemplate>
  23. </ListView.ItemTemplate>
  24. </ListView>
  25. </StackPanel>


This question似乎也有类似的问题,但在工作解决方案上答案并不清楚。

pod7payv

pod7payv1#

试试这个方法:
1.使用x:Name命名您的页面。

  1. <Page x:Name="RootPage" ...>

字符串
1.使用BindingElementNamePath绑定代码隐藏属性 MyName

  1. <DataTemplate x:DataType="local:MyCar">
  2. <!-- Doesn't compile.
  3. <TextBlock Text="{x:Bind MyName, Mode=OneWay}" />
  4. -->
  5. <!-- Doesn't compile.
  6. <TextBlock Text="{x:Bind RootPage.MyName, Mode=OneWay}" />
  7. -->
  8. <!-- Compiles but the binding fails and doesn't work.
  9. <TextBlock Text="{Binding RootPage.MyName}" />
  10. -->
  11. <TextBlock Text="{Binding ElementName=RootPage, Path=MyName}" />
  12. </DataTemplate>


因为你使用的是ListView,所以上面的代码可以工作,但是如果你改变主意,想使用ItemsRepeater,它就不能工作了。
ElementName bindings don't work inside ItemsRepeater DataTemplate #560

展开查看全部
vuktfyat

vuktfyat2#

一个简单的解决方案是命名页面,然后从绑定中引用它:

  1. <Page x:Name="RootPage" ...>
  2. <TextBlock x:Name="OwnerTextBlock" Text="{x:Bind MyName, ElementName=RootPage}" />

字符串

相关问题