0

我需要创建一些控件,就像那样类似于具有自动生成的文本框字段的 ListBox

首先我必须有 1 个空字段。在我在该字段中写入一些文本后,将出现新字段。等等。如果我从字段中删除所有文本 - 旧(右)字段也会被删除。

在我的项目中,我使用 MVVM。我想到了带有 TextBox DataTemplate 的 ListBox。但是不明白如何正确使用事件或其他东西。任何人都有一些想法或可能知道 WPF 的现成控件?

谢谢!

4

1 回答 1

0

问题解决了。主要思想 - 通知和处理集合中每个项目中的 PropertyChange 事件。

我们的观点:

<ListBox    Name="TrunkListBox" Height="160"
ItemsSource="{Binding YourSource}"
ItemTemplate="{DynamicResource YourDataTemplate}"/>


<DataTemplate x:Key="YourDataTemplate">
    <TextBox Width="200" Text="{Binding Number,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
//VM for notification about propertyChange
public class TrunkElementViewModel : NotificationObject
{
    private string _number = string.Empty;
    public string Number 
    {
        get { return _number; }
        set
        {
            _number=value;
            RaisePropertyChanged(() => Number);
        }
    }
}
//In my class when I initialize my data -add trunk_PropertyChanged event handler each element + add empty element
void SomeInit()
{
    if( SomeCollection already have items)
    {
    //get element and add event handler
    foreach (var item in SomeCollection)
    {
        var trunk = new TrunkElementViewModel { Number = substring };
        trunk.PropertyChanged += trunk_PropertyChanged;
        TrunkNumbers.Add(trunk);
    }
    //add empty element(must be everytime)
    var emptyTrunk = new TrunkElementViewModel();
    emptyTrunk.PropertyChanged += trunk_PropertyChanged;
    TrunkNumbers.Add(emptyTrunk);
}
//Hadling changing element event - add new empty item or remove empty
    void trunk_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    var trunk = sender as TrunkElementViewModel;
    var positionElement = TrunkNumbers.IndexOf(trunk);
    //add new item in list
    if (TrunkNumbers.LastOrDefault() == trunk)
    {
        var nextTrunk = new TrunkElementViewModel();
        nextTrunk.PropertyChanged += trunk_PropertyChanged;
        TrunkNumbers.Add(nextTrunk);
    }
    //remove item from list
    else if (trunk.Number == string.Empty && TrunkNumbers.LastOrDefault() != trunk)
    {
        trunk.PropertyChanged -= trunk_PropertyChanged;
        TrunkNumbers.Remove(trunk);
    }   
}
于 2013-11-07T14:11:51.887 回答