簡體   English   中英

wp7中列表框內的文本框更改用戶在滾動時輸入的值

[英]TextBoxes inside listbox in wp7 changing the values entered by user while scrolling

我有一個列表框

            <ListBox Name="lstbox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBox Name="text" Background="White" Foreground="Black" Width="400"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

這是C#代碼

    List<string> lst = new List<string>();
    // Constructor
    public MainPage()
    {
        for (int i = 0; i < 100; i++)
        {
            lst.Add("a"+i.ToString());
        }
        lstbox.ItemsSource = lst;
    }

我希望用戶在列表框中的文本框中輸入值。 值將永久顯示在文本框中。 但是,當我在文本框中輸入值時,它也在其他文本框中顯示該值。 同樣,當我滾動列表時,在文本框中輸入的值也會丟失。 請幫忙

我也可以嘗試同樣的怪異行為。 我建議您嘗試將列表轉換為實現INotifyPropertyChanged接口的某種模型。 似乎您希望從UI(文本框)進行的更改也反映在集合中,因此這是更好/更干凈的方法恕我直言。

XAML

<ListBox Name="lstbox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Name, Mode=TwoWay}" Background="White" Foreground="Black" Width="400"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

后面的代碼

public partial class MainPage : PhoneApplicationPage
{
    private readonly ObservableCollection<Customer> customers = new ObservableCollection<Customer>();

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        for (int i = 0; i < 100; i++)
        {
            customers.Add(new Customer { Name =" Customer " + i });
        }

        lstbox.ItemsSource = customers;
    }
}

public class Customer : INotifyPropertyChanged
{
    private string name;

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public string Name
    {
        get { return this.name; }

        set
        {
            if (value != this.name)
            {
                this.name = value;
                OnPropertyChanged();
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM