绑定ObservableCollection <item>到TextBox(UWP)

时间:2016-11-02 09:50:47

标签: c# xaml uwp

我想从ObservableCollection实现单向绑定&#34; struct-like&#34;具有TextChanged事件的TextBox的项目。这个想法是,当Item的Comments字段在TextBox中累积时,TextBox会自动向下滚动,以便最后一行始终在视图中。该集合绑定到ListView,但我希望它以只读方式绑定到TextBox。我不想在ResultViewModel中添加另一个方法,而是在XAML中执行。我该怎么做呢? TIA

// ViewModel

public class Item
    {        
        public string First { get; set; }

        public string Last { get; set; }

        public string Comments { get; set; }
    }

public class ResultViewModel
    {
        private ObservableCollection<Item> items = new ObservableCollection<Item>();                                          

    public ObservableCollection<Item> Items { get { return items; } }

        // member functions
    }

public ResultViewModel ViewModel { get; set; }

// What I have

            <ListView x:Name="myListView" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"                      
                  ItemsSource="{x:Bind ViewModel.Items}">
                <ListView.ItemTemplate>
                    <DataTemplate x:DataType="local:Item">
                        <StackPanel>
                            <TextBox Text="{x:Bind First}"/>
                            <TextBlock Text="{x:Bind Last}"/>
                            <TextBlock Text="{x:Bind Comments}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

// What I want

<TextBox Text="{x:Bind Comments}"/>

1 个答案:

答案 0 :(得分:1)

我担心你不能单独使用XAML。 您可以创建一个行为,该行为将在修改集合时监听事件并向文本框添加行。

肮脏的例子,你需要包含Microsoft.Xaml.Behaviors.Uwp.Managed包:

public class CommentsBehavior : Behavior
{
    public ObservableCollection<string> Comments ... // you will need to make it a dependency property

    protected virtual void OnAttached()
    {
        Comments.CollectionChanged += OnCollectionChanged;
    }

    protected virtual void OnDetaching()
    {
        Comments.CollectionChanged -= OnCollectionChanged;
    }

    private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach(string newItem in e.NewItems)
            {
                ((TextBox)AssociatedObject).Text = ((TextBox)AssociatedObject).Text + '\n' + newItem;   
            }
        }
    }
}

滚动 - UWP C# Scroll to the bottom of TextBox

但为什么要使用文本框呢?使用列表更有意义。

相关问题