WPF Listbox binding

与世无争的帅哥 提交于 2019-12-05 14:15:58
Phil

Mike, there are few problems with your bindings. Here's a complete sample demonstrating one way of doing what (I think) you're after.

View:

<Page.Resources>
    <ViewModel:Physician x:Key="physician"/>
</Page.Resources>
<StackPanel DataContext="{StaticResource physician}" >
    <TextBlock Text="{Binding Name}" Background="Orange"/>
    <TextBlock Text="Works in:"/>
    <ListBox ItemsSource="{Binding Clinics}" 
             SelectedValue="{Binding SelectedClinicId}" 
             SelectedValuePath="Id" DisplayMemberPath="Name" />
</StackPanel>

View model:

public class Physician
{
    private int _selectedClinicId;

    public Physician()
    {
        Name = "Overpaid consultant";
        Clinics = new ObservableCollection<Clinic>
                      {
                          new Clinic {Id = 0, Name = "Out Patients"},
                          new Clinic {Id = 1, Name = "ENT"},
                          new Clinic {Id = 2, Name = "GE"},
                      };
    }

    public string Name { get; set; }
    public IEnumerable<Clinic> Clinics { get; private set; }

    public int SelectedClinicId
    {
        get { return _selectedClinicId; }
        set
        {
            if (value != _selectedClinicId)
            {
                Debug.WriteLine(string.Format("setting clinic to: {0}",value));
                _selectedClinicId = value;
            }
        }
    }
}

public class Clinic
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Note that for read/write properties you would probably want to raise property change notifications.

Your issue is SelectedValue. At the ListBox level, binding to multiple selection objects is not supported. The only real way to do this with bindings would be to rework your ViewModel so that the list of clinics returned from the binding represents all clinics, and each object there should have an IsSelected (or something similar) property.

You can then use a style to handle the multi selection by adding this XAML within your ListBox node:

<ListBox.ItemContainerStyle>
   <Style TargetType="{x:Type ListBoxItem}">
      <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
   </Style>
</ListBox.ItemContainerStyle>
paparazzo

You are going to need to use a template with TextBox for name and ListBox for Clinics and you just bind the internal ListBox path to Clinics. DisplayMemberPath is a short cut a single TextBox. If you want more then you need individual controls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!