C# WPF 列表框绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9368506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:03:43  来源:igfitidea点击:

WPF Listbox binding

c#wpfbindinglistboxobservablecollection

提问by Mike Malter

I have a physician object, and one of its properties is an ObservableListof clinics. It is being used in a window to show the details of a physician. I can get individual properties to bind to TextBoxand ComboBoxcontrols, but I can't get the list of clinics to bind to my ListBox.

我有一个医生对象,它的一个属性是ObservableList诊所。它被用在一个窗口中以显示医生的详细信息。我可以获取要绑定到的单个属性TextBoxComboBox控件,但是我无法获取要绑定到我的ListBox.

Here is the xaml for my ListBox:

这是我的 xaml ListBox

<ListBox Height="318" 
 HorizontalAlignment="Left" 
 Margin="422,0,0,0" 
 Name="lbClinic" 
 VerticalAlignment="Top" 
 Width="158" 
 SelectedValue="{Binding ClinicID, Path=Clinics, Mode=TwoWay, 
                          UpdateSourceTrigger = PropertyChanged}"
 SelectedValuePath="ClinicID" 
 DisplayMemberPath="Name"
 ItemsSource="{Binding DataContext.ClinicList, 
                          ElementName = PhysicianInfoLookup, Mode = OneWay}" 
 SelectionMode="Multiple" />

The Listbox populates properly with items from the ClinicList which is a list of all possible clinics. However, I cannot get the Clinics list from the physician object to bind so that it's items are selected in the Listbox. I also want to go the other way and if an item is deselected, the ObservableList in the physician object will change accordingly.

Listbox 使用 ClinicList 中的项目正确填充,ClinicList 是所有可能诊所的列表。但是,我无法从要绑定的医师对象中获取诊所列表,以便在列表框中选择它的项目。我也想反其道而行之,如果取消选择某个项目,则医生对象中的 ObservableList 将相应更改。

How do I two-way bind the ObservableList of Clinics in my physician object to the list of Clinics (ObservableList of clinic objects) in my Listbox?

如何将医生对象中的诊所的 ObservableList 双向绑定到列表框中的诊所列表(诊所对象的 ObservableList)?

Thank you.

谢谢你。

回答by paparazzo

You are going to need to use a template with TextBoxfor name and ListBoxfor Clinics and you just bind the internal ListBoxpath to Clinics. DisplayMemberPathis a short cut a single TextBox. If you want more then you need individual controls.

您将需要使用带有TextBoxfor name 和ListBoxfor Clinics的模板,您只需将内部ListBox路径绑定到 Clinics。 DisplayMemberPath是一条捷径单TextBox。如果您想要更多,则需要单独的控件。

回答by 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.

请注意,对于读/写属性,您可能希望引发属性更改通知。

回答by Adam Robinson

Your issue is SelectedValue. At the ListBoxlevel, 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 allclinics, and each object there should have an IsSelected(or something similar) property.

你的问题是SelectedValue。在ListBox级别上,不支持绑定到多个选择对象。使用绑定做到这一点的唯一真正方法是重新设计您的 ViewModel,以便从绑定返回的诊所列表代表所有诊所,并且那里的每个对象都应该有一个IsSelected(或类似的)属性。

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

然后,您可以通过在ListBox节点中添加此 XAML 来使用样式来处理多选:

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