总结一下wpfMvvm下拉框数据的绑定与回填,下拉框的选择是很常见的一个功能,随这场景的变化我们要如何合理的使用下拉框的绑定方式,我这里一共讲两种方式的绑定和回填。
第一种,也是比较常见的一种通过查询数据库内的数据绑定成下拉框
<ComboBox Width="160" ItemsSource="{Binding CustomerInformation}" DisplayMemberPath="CustomerName" SelectedValuePath="CustomerInformationID"
SelectedValue="{Binding CustomerInformationID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></ComboBox>
首先XML上的一个下拉框组件设置ItemsSource="{Binding CustomerInformation}" 这样一个属性这就是设置数据源的。这个 SelectedValue="{Binding CustomerInformationID} 设置的是当前选中的值。
在后台是创建一个List一个显示值,一个选中值,选中值的名称和页面上的ItemsSource的Binding一样这样它们之间就可以关联上。
private List<S_CustomerInformation> _CustomerInformation;
public List<S_CustomerInformation> CustomerInformation
{
get { return _CustomerInformation;
}
set{
if (_CustomerInformation != value)
{
_CustomerInformation = value;
RaisePropertyChanged(() => CustomerInformation);
}
}
}
然后就是去查询数据库数据把数据给到选中值,这样就可以就可以把数据绑定到下拉框的下拉项上。
List<S_CustomerInformation> dbSiteInformation = (
from tbSiteInformation in myModel.S_CustomerInformation
select tbSiteInformation).ToList();
如果我们需要数据回填那就是SelectedValue="{Binding CustomerInformationID}值和绑定我们的下拉项一样先在后台绑定Binding,然后回填时就直接给查询出来的ID就行了。
第二种:如果说我们想直接给下拉框的下拉项,我们可以在页面上直接给下拉项。在页面上我们可以直接给<ComboBoxItem Content="禁用"></ComboBoxItem>这个下拉项,要什么就给什么,然后我们获取的话就是直接给下拉框的Text属性一个Binding,然后在后台绑定这个Binding,我们的下拉框选中值就是binding的值,其实简单一点说就是下拉框的文本值。
<ComboBox Grid.Row="15" Grid.Column="3" Height="35" FontSize="14" x:Name="Jinyong" Text="{Binding Cuisine}" >
<ComboBoxItem Content="禁用"></ComboBoxItem>
<ComboBoxItem Content="不禁用"></ComboBoxItem>
</ComboBox>
/// <summary>
/// 下拉框
/// </summary>
public string _Cuisine;
public string Cuisine
{
get { return _Cuisine; }
set
{
if (_Cuisine != value)
{
_Cuisine = value;
RaisePropertyChanged(() => Cuisine);
}
}
}
那如果说我们用这种方式来进行下拉框的绑定和选择,那我们的数据库保存的就是一串字符串,如果我们需要进行数据回填的话也很简单就是把数据查询出来给到下拉框的Text属性的Binding值就好了,那么它的文本值就是你数据库中的值了。换个角度来看其实就是你的下拉框选中值。