数据模板和列表框之间的绑定 - Windows Phone



我在Windows Phone中进行绑定时遇到问题。希望你能帮助我。

我有以下数据模板:

<DataTemplate>

<TextBox Name="txt1"/> <TextBox Name="txt2"/> </DataTemplate>



我有一个列表框,它在 ItemsSource 属性中接收以下类:

public class Product
{
    private int _id;
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

无论如何,是否可以将 Text 属性与列表框项的对象绑定,例如...

<TextBox Name="txt1" Text={Binding ElementName=ListBox, Path=SelectedItem.Product.Name}/>

我有一个工作示例XAML:这是代码

<Grid x:Name="gdTest" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  Margin="5,0,5,0" >
    <ListBox Width="400" Margin="10" x:Name="lstDemo">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Id}" Margin="20" />
                    <TextBlock Text="{Binding Path=Name}" Margin="20"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

XAML.cs

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using StackOverFlowTestApp.Resources;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.UserData;
using Windows.UI;
using System.Windows.Media;
using System.IO;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;
namespace StackOverFlowTestApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        private SoundEffect effect;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            List<Product> liProd = new List<Product>();
            for (int i = 0; i < 10; i++) {
                liProd.Add(new Product()
                {
                    Id = i,
                    Name = "Anobik" + i.ToString()
                });
            }
            lstDemo.ItemsSource = liProd;
        }

    }
    public class Product
    {
        private int _id;
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    }

如果您需要更多解释,请告诉我。

相关内容

  • 没有找到相关文章