How to associate a Listview SelectedItem with a text field in TwoWay mode?

I am very new to WPF and testing some things that I would like to include in the application that I will work on. I have a 2-row ListView (associated with a text box) with the names of Scott Guthrie and John Skeet. I am trying to select "Scott Guthrie" in a ListView and populate a TextBox. I want to be able to edit and exit text and update ListView.

Edit : I deleted the code since it really added nothing to the question.

+3
source share
2 answers

Wow, that really complicated what you have there.

. , .

:

public sealed class Programmer
{
    public string Name { get; set; }
}

. , . , .NET. , .

ViewModel. ViewModel, . , . .

public sealed class ViewModel
{
    public ObservableCollection<Programmer> Programmers { get; private set; }

    public ViewModel()
    {
        Programmers = new ObservableCollection<Programmer>();
    }
}

ViewModel DataContext . DataContext , .

public MainWindow()
{
    var vm = new ViewModel();
    vm.Programmers.Add(new Programmer { Name = "Jon Skeet" });
    vm.Programmers.Add(new Programmer { Name = "Scott Guthrie" });
    DataContext = vm;
    InitializeComponent();
}

DataContext ; .

ListView Programmers ViewModel (DataContext, , ). TextBox SelectedItem ListBox. Programmer , SelectedItem, Name.

<Window
    x:Class="Programmers.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:t="clr-namespace:Programmers"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <ListBox
            x:Name="list"
            ItemsSource="{Binding Programmers}"
            DisplayMemberPath="Name" />
        <TextBox
            Grid.Column="1"
            VerticalAlignment="Top"
            Text="{Binding SelectedItem.Name, ElementName=list}" />
    </Grid>
</Window>

, .

+28

( , , .. ).

:

<TabItem x:Name="RightTabPage" Header="RightModel"  DataContext="{Binding Right}">
                    <StackPanel>
                        <TextBox Text="{Binding SelectedGuru}"/>
                        <ListView SelectedItem="{Binding SelectedGuru}" ItemsSource="{Binding Gurus}"/>
                    </StackPanel>
                </TabItem>

ViewModel:

public class RightViewModel
    {
        public RightViewModel()
        {
            Gurus = new[] {"Scott Guthrie", "Jon Skeet"};
            SelectedGuru = Gurus.First();
        }

        public string SelectedGuru { get; set; }
        public IEnumerable<string> Gurus{ get; set; }
    }
+5

Source: https://habr.com/ru/post/1782049/


All Articles