【问题标题】:uwp: how to bind data inside DataTemplate outside of x:DataType?uwp:如何在 x:DataType 之外的 DataTemplate 中绑定数据?
【发布时间】:2020-10-22 19:53:59
【问题描述】:

我有 MyPage.xaml 和 MyPage.xaml.cs 文件。 在 .xaml 文件中,我写了一个这样的数据模板:

        <DataTemplate x:Key="MyDataTemplate" x:DataType="local:MyClass">
            ...
            <TextBlock Text="{x:Bind name}" HorizontalAlignment="Left" TextWrapping="Wrap"/>
            ...
        </DataTemplate>

我可以正确绑定 MyClass 的 name 属性。 现在我需要绑定 .xaml.cs 文件的属性,但 DataTemplate 只显示 MyClass 数据。如何从 .xaml.cs 页面绑定数据?在 DataTemplate 之外(但在同一个 xaml 文件中)我可以看到 .xaml.cs 文件的任何属性。 我需要将对象列表绑定到这样的组合框:

<ComboBox ItemsSource="{x:Bind myList}" HorizontalAlignment="Left"></ComboBox>

但 myList 是一个 .xaml.cs 属性。 我想查看列表对象的字符串名称属性。

感谢您的帮助

【问题讨论】:

  • 我通常使用 WPF,所以我不知道它是否有效,但您可以尝试在页面中添加名称,例如:&lt;Page x:Name="page" ... &gt; 并在 ComboBox 中:ItemsSource="{x:Bind myList ElementName=page}"

标签: c# uwp combobox bind


【解决方案1】:

uwp:如何在 x:DataType 之外的 DataTemplate 中绑定数据?

建议您使用Binding 替换x:Bind,您可以使用Binding 访问当前根DataContext 和ElementName

例如

<Grid x:Name="GridRoot">
    <ListView ItemsSource="{Binding Items}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <ComboBox ItemsSource="{Binding ElementName=GridRoot, Path=DataContext.Options}" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

代码背后

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }
    public List<string> Options { get; set; } = new List<string>() {"One","Two","Three" };
    public List<Item> Items { get; set; } = new List<Item>() 
    { 
        new Item { Name = "HH" },
        new Item { Name = "ZZ" }, 
        new Item { Name = "MM" }
    };
}
public class Item
{
    public string Name { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-13
    • 2020-02-01
    • 2017-09-10
    • 2020-04-07
    • 2016-03-23
    • 2020-11-05
    • 2016-12-27
    • 1970-01-01
    相关资源
    最近更新 更多