使用标记方法将 Item Sourcing 转换为 ComboBox

Convert Item Sourcing a ComboBox using a method to markup

我有一个ComboBox

<ComboBox x:Name="SearchGendersComboBox" Grid.Row="3" Grid.Column="1"
                          IsEditable="True"
                          SelectedValuePath="Key"
                          DisplayMemberPath="Value"
                          SelectedValue="{Binding Path=GenderId}"

                          />

我用这个来填充它:

public void BindComboBoxes()
{            
    SearchGendersComboBox.ItemsSource = new BindingSource(GenderMgr.GetGendersDropDown(true), null);            
    SearchGendersComboBox.SelectedIndex = 0;
}

这是 GenderMgr:

public class GenderMgr
{

    public static Dictionary<byte, string> GetGendersDropDown(bool isFilterMode = false)
    {
        return GenderDb.RetrieveGendersDropDown(isFilterMode);
    }

}

如何使用标记中的 GenderMgr.GetGendersDropDown 填写 ComboBox

去掉BindingSourceItemsSource应该直接是GenderMgr.GetGendersDropDown(true),即字典。其他一切看起来都很好。

至于转换为标记:在某些时候你需要从某个地方获取对象,所以除了使用 ObjectDataProvider 调用相应的数据提供方法之外你无能为力 XAML.通常你会有一些 属性 来保存视图模型中的项目,然后 ItemsSource 仍然可以绑定在 XAML 中;只要视图模型支持更改通知,属性 就可以在数据可用的任何时候分配。