Having trouble binding ViewModel to ComboBox

妖精的绣舞 提交于 2019-12-14 04:09:35

问题


I have a viewmodel setup as the following

public class cDriveListVM
{
    public string Drive { get; set; }
    public cDriveListVM(string name)
    {
        Drive = name;
    }
}

I declare the observablecollection in the window and set its datacontext to this observable collection.

public ObservableCollection<cDriveListVM> DriveList { get; set; }
private void dl()
{
    DriveList = new ObservableCollection<cDriveListVM>();
    DriveList.Add(new cDriveListVM("drive 1"));
    DriveList.Add(new cDriveListVM("drive 2"));
    this.DataContext = DriveList;
}

Xml for combobox:

<ComboBox x:Name="Drive_ComboBox" ItemsSource="{Binding Path=Drive}" HorizontalAlignment="Center" IsReadOnly="True" Grid.Column="0" Grid.Row="0" Width="300" Margin="10" SelectionChanged="Drive_Changed" Height="22" VerticalAlignment="Top"/>

I am just learning how to use Viewmodel so I am unsure what I am doing wrong, any help would be appreciated. I updated the xml file it results in the following combbox.


回答1:


There are a few problems with this code.

One, the binding is set up wrong. Since the property with the viewmodel collection is DriveList, the binding should be ItemsSource="{Binding Path=DriveList}".

Two, you are attempting to display a field from your viewmodel, which is not doable. WPF's binding engine only works with properties, so the viewmodel should have a property:

public string Drive { get; set; }

And finally, the DisplayMemberPath should match the property name from the viewmodel: DisplayMemberPath="Drive".

Update: I just noticed that the DataContext is the observable collection itself -- I probably missed it on the first read. In that case, you want to bind directly to the data context:

ItemsSource="{Binding}"

And set DisplayMemberPath to the property you want to display:

DisplayMemberPath="Drive"


来源:https://stackoverflow.com/questions/18242301/having-trouble-binding-viewmodel-to-combobox

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