根据ListBox XAML中的选定值填充TextBox

时间:2014-11-13 11:38:13

标签: c# wpf xaml listbox

所以,我有这个班级

public class Multimedia : INotifyPropertyChanged
{
    private string title;
    private string artist;
    private string genre;
    private MediaType type;
public Multimedia (string _title, string _artist, string _genre, MediaType _type)
{
    this.title = _title;
    this.artist = _artist;
    this.genre = _genre;
    this.type = _type;
}

public String Title { get { return this.title; } }
public String Artist { get { return this.artist; } }
public String Genre { get { return this.genre; } }
public MediaType Type { get { return this.type; } }

public event PropertyChangedEventHandler PropertyChanged;

}

我存储对象的集合:

public class MultiMediaList : ObservableCollection<Multimedia>
    {
        public MultiMediaList()
        {
            Add(new Multimedia("YMCA", "Village People", "disco", MediaType.CASSETTE));
            Add(new Multimedia("Free", "Rudimental", "D&B/Liquid", MediaType.DVD));
            Add(new Multimedia("November Rain", "Guns'n'Roses", "rock", MediaType.CD));
        }
    }

ListBox的XAML:

<ListBox Name="LB_media" SelectionChanged="ListBox_SelectionChanged" DisplayMemberPath="Title" />

窗口的代码隐藏:

MultiMediaList mediaList;
        public MainWindow()
        {
            InitializeComponent();
            mediaList = new MultiMediaList();
            LB_media.ItemsSource = mediaList;
        }

ListBox我填充了集合中对象的 Title 属性值。现在,我有代码隐藏功能,填充其他3个TextBox元素(对于属性 Title Artist Genre ,我想填充它们具有相应的属性值,具体取决于ListBox中的哪个项目被选中。但是,我可以在XAML中执行此操作吗?

2 个答案:

答案 0 :(得分:1)

您必须为周围容器设置DataContext:

<StackPanel DataContext="{Binding ElementName=LB_media, Path=SelectedItem}">
    <TextBox x:Name="tbArtist" Text="{Binding Artist}" />
    [..]
</StackPanel>

您可以直接访问SelectedItem,但此解决方案更加优雅且更加强大。如果您决定更改DataContext,则只需要替换一行。

答案 1 :(得分:1)

您可以绑定SelectedItem

ListBox的媒体资源
<StackPanel>
    <TextBox Text="{Binding ElementName=LB_media, Path=SelectedItem.Artist, Mode=OneWay}" IsReadOnly="True"/>
    <TextBox Text="{Binding ElementName=LB_media, Path=SelectedItem.Genre, Mode=OneWay}" IsReadOnly="True"/>
    <TextBox Text="{Binding ElementName=LB_media, Path=SelectedItem.Type, Mode=OneWay}" IsReadOnly="True"/>
</StackPanel>

因为您使用TextBox而且属性是只读的,所以您必须使用Mode=OneWay,否则您会遇到一些例外情况