将 ViewModel 绑定到 ComboBox 时遇到问题 [英] Having trouble binding ViewModel to ComboBox
问题描述
我的视图模型设置如下
public class cDriveListVM
{
public string Drive { get; set; }
public cDriveListVM(string name)
{
Drive = name;
}
}
我在窗口中声明了 observablecollection 并将其 datacontext 设置为这个 observable 集合.
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:
<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"/>
我只是在学习如何使用 Viewmodel,所以我不确定我做错了什么,任何帮助将不胜感激.我更新了 xml 文件,结果是以下组合框.
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.
推荐答案
这段代码存在一些问题.
There are a few problems with this code.
一、绑定设置错误.由于 viewmodel 集合的属性是 DriveList
,所以绑定应该是 ItemsSource="{Binding Path=DriveList}"
.
One, the binding is set up wrong. Since the property with the viewmodel collection is DriveList
, the binding should be ItemsSource="{Binding Path=DriveList}"
.
二,您试图从您的视图模型中显示一个字段,这是不可行的.WPF 的绑定引擎只对属性起作用,所以视图模型应该有一个属性:
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; }
最后,DisplayMemberPath
应与视图模型中的属性名称匹配:DisplayMemberPath="Drive"
.
And finally, the DisplayMemberPath
should match the property name from the viewmodel: DisplayMemberPath="Drive"
.
更新:我刚刚注意到 DataContext
本身就是可观察的集合——我可能在第一次阅读时错过了它.在这种情况下,您希望直接绑定到数据上下文:
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}"
并将 DisplayMemberPath
设置为要显示的属性:
And set DisplayMemberPath
to the property you want to display:
DisplayMemberPath="Drive"
这篇关于将 ViewModel 绑定到 ComboBox 时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!