Home > front end >  WPF bind list box Selected item into textbox
WPF bind list box Selected item into textbox

Time:05-13

I'm trying to put any selected item's name in my list box in the textbox next to it. But I've got trouble doing so.

listbox image

Here's a little bit of my code:

    <DockPanel Margin="10">
        <StackPanel Margin="5" DockPanel.Dock="Left">
            <ListBox   Name="lbNames" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True"/>
        </StackPanel>
        <StackPanel Margin="5" DockPanel.Dock="Right">
            <TextBox Name="txtName" Width="auto" Text="{Binding ElementName=lbNames,Path=SelectedItem}"/>
            <WrapPanel Margin="0,5" Orientation="Horizontal">
                <Button Margin="2,0" Name="btnAdd" Click="btnAdd_Click" Content="Add"/>
                <Button Margin="2,0"  Name="btnEdit" Click="btnChange_Click" Content="Edit"/>
                <Button Margin="2,0"  Name="btnDelete" Click="btnDelete_Click" Content="Delete"/>
            </WrapPanel>
        </StackPanel>
    </DockPanel>

CodePudding user response:

Because you are showing Text="{Binding ElementName=lbNames,Path=SelectedItem}"and your selected item is an user object. Instead of this you can use something like that. First add SelectedValuePath="Name" into your listbox. Then use Text="{Binding ElementName=lbNames,Path=SelectedValue}"

 <DockPanel Margin="10">
    <StackPanel Margin="5" DockPanel.Dock="Left">
        <ListBox   Name="lbNames" DisplayMemberPath="Name" SelectedValuePath="Name" IsSynchronizedWithCurrentItem="True"/>
    </StackPanel>
    <StackPanel Margin="5" DockPanel.Dock="Right">
        <TextBox Name="txtName" Width="auto" Text="{Binding ElementName=lbNames,Path=SelectedValue}"/>
        <WrapPanel Margin="0,5" Orientation="Horizontal">
            <Button Margin="2,0" Name="btnAdd" Click="btnAdd_Click" Content="Add"/>
            <Button Margin="2,0"  Name="btnEdit" Click="btnChange_Click" Content="Edit"/>
            <Button Margin="2,0"  Name="btnDelete" Click="btnDelete_Click" Content="Delete"/>
        </WrapPanel>
    </StackPanel>
</DockPanel>

Or simply you can use it too Text="{Binding ElementName=lbNames,Path=SelectedItem.Name}"

  • Related