开发者

How to bind a TextBox to plain string collection

开发者 https://www.devze.com 2022-12-11 01:44 出处:网络
As a part of large data model I need to display/edit a string collection defined like ObservableCollection<String>. In prototype app we use a list view to display entire of collection and a text

As a part of large data model I need to display/edit a string collection defined like ObservableCollection<String>. In prototype app we use a list view to display entire of collection and a text box to edit selected element. T开发者_StackOverflow社区he text box should be bound to the current element of the collection. Because GUI is subject to change I can't bind directly using <TextBox Text="{Binding SelectedItem,ElementName=listView}" />.

I tried to use

<TextBox Text="{Binding Path=/, UpdateSourceTrigger=PropertyChanged}"/>

but it works only in one direction, changing listview current item causes updating a text box but not otherwise.

How can I bind a text box directly to sting instance of current element in string collection?


Ok, so here's your ListView. I'm going to add a name to it so I can reference it elsewhere in the XAML:

<ListView 
    x:Name=stringList
    ItemsSource="{Binding}" 
    SelectionMode="Single" 
    IsSynchronizedWithCurrentItem="True">
    <ListView.View>
        <GridView>
            <GridViewColumn 
                Header="Data Item" 
                Width="80" 
                DisplayMemberBinding="{Binding}"/>
        </GridView>
    </ListView.View>
</ListView>

Now in your TextBox over on the right you can bind directly to the ListView:

<TextBox Text="{Binding SelectedItem,ElementName=stringList}" />

Since your ListView is bound directly to a list of strings, SelectedItem will be the string the currently-selected ListViewItem points to.

Update

Since you're not allowed to use ElementBinding, your best bet is to introduce a ViewModel class to sit between your list and your window. Define it like this:

public class StringListViewModel : INotifyPropertyChanged
{
    // you'll have to implement INotifyPropertyChanged - I won't
    // do that here - do a quick search to learn how it works.

    public ObservableCollection<String> List { get; set; }

    private object _si;
    public object SelectedItem
    {
        get { return _si; }
        set
        { 
            _si = value;
            OnPropertyChanged("SelectedItem");
        }
    } 
}

Now set your window's DataContext to an instance of your ViewModel class instead of pointing it directly to the string list. Bind your ListView's ItemsSource and SelectedItem to it like this:

<ListView ItemsSource="{Binding List}" SelectedItem="{Binding SelectedItem}" ... />

Now bind your TextBox to the SelectedItem of your ViewModel:

<TextBox Text="{Binding SelectedItem}" />

Now your list sets the SelectedItem on the ViewModel whenever it changes, and thus your TextBox reflects that value. Hope that makes sense.

0

精彩评论

暂无评论...
验证码 换一张
取 消