wpf 使用 Id 值绑定组合框名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24549521/
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-09-13 12:04:20  来源:igfitidea点击:

Binding Combobox Name using Id value

c#wpfxamlcombobox

提问by JohnPaul

I have a combobox control. I am getting combobox values from Database. There I have Id and Name. But I am binding only Name in the combobox. what i want is, 1. If I select any name in the Combobox, I need to save the Corresponding Id in my Database. Now I am able to bind the value from database and Display the Name in Combobox. but when I select any value in combobox and try to save means, it shows null value on the ID. Here is my code. Please help me to find some solution. Xaml:

我有一个组合框控件。我从数据库中获取组合框值。在那里我有 Id 和 Name。但我只绑定了组合框中的 Name。我想要的是, 1. 如果我在组合框中选择任何名称,我需要在我的数据库中保存相应的 Id。现在我可以绑定数据库中的值并在组合框中显示名称。但是当我在组合框中选择任何值并尝试保存手段时,它在 ID 上显示空值。这是我的代码。请帮我找到一些解决办法。Xml:

    <ComboBox x:Name="cb_rentaltype" HorizontalAlignment="Left" Margin="150,5,0,0"    VerticalAlignment="Top" Height="35" Width="200"
                                          SelectedValue="{Binding MasterRentalType}"
                                          DisplayMemberPath="RentalTypeName"
                                          SelectedValuePath="RentalTypeId" />

My code Behind:

我的代码背后:

        var status = new MasterRentalType();
        List<MasterRentalType> listRentalType =
                              status.Get<MasterRentalType>() as
                               List<MasterRentalType>;

        cb_rentaltype.ItemsSource = listRentalType;

and i want to bind the Id to the Data context. here is the code,

我想将 Id 绑定到数据上下文。这是代码,

 private void FacilityDataBind()
    {
        cb_rentaltype.DataContext = ??
    }

Note: MasterRentalType is the Table where i get the Values. There I have ID and Name values.

注意:MasterRentalType 是我获取值的表。在那里我有 ID 和 Name 值。

  public class MasterRentalType : EntityBase
     {
        public string RentalTypeId {get; set;}
        public string RentalTypeName {get; set;}       
     }

how can I bind and save the id value?

如何绑定和保存 id 值?

回答by Sheridan

Your problem is caused because you have data bound the ComboBox.SelectedValueproperty to your MasterRentalTypeproperty, which I assume is of type MasterRentalType, but then you set the SelectedValuePathproperty to RentalTypeId. So you're saying *make the SelectedValueuse the string RentalTypeIdproperty, but then data binding a MasterRentalTypeto it.

您的问题是因为您有数据将ComboBox.SelectedValue属性绑定到您的MasterRentalType属性,我认为它的类型是MasterRentalType,但随后您将该SelectedValuePath属性设置为RentalTypeId. 所以你是说 *make the SelectedValueusestring RentalTypeId属性,然后将数据绑定MasterRentalType到它。

There are a number of solutions. Correcting your example, you should try this:

有多种解决方案。纠正你的例子,你应该试试这个:

<ComboBox x:Name="cb_rentaltype" HorizontalAlignment="Left" Margin="150,5,0,0" 
    SelectedValue="{Binding MasterRentalType.RentalTypeId}"
    DisplayMemberPath="RentalTypeName"
    SelectedValuePath="RentalTypeId" />

Alternatively, you could have done this:

或者,您可以这样做:

<ComboBox x:Name="cb_rentaltype" HorizontalAlignment="Left" Margin="150,5,0,0" 
    SelectedItem="{Binding MasterRentalType}"
    DisplayMemberPath="RentalTypeName" />

To find out more about the differences, please take a look at the How to: Use SelectedValue, SelectedValuePath, and SelectedItempage on MSDN.

要了解有关差异的更多信息,请查看MSDN上的如何:使用 SelectedValue、SelectedValuePath 和 SelectedItem页面。

回答by Debasis

There are several ways to achieve this. One of them is implemented below:

有几种方法可以实现这一点。其中之一在下面实现:

The xaml should look like this:

xaml 应如下所示:

<ComboBox x:Name="cb_rentaltype" HorizontalAlignment="Left" Margin="150,5,0,0" 
              ItemsSource="{Binding MasterRentalTypeColl, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
              SelectedItem="{Binding SelectedMasterRentalType, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
              DisplayMemberPath="RentalTypeName">            
    </ComboBox>

The MasterRentalTypeclass:

MasterRentalType类:

public class MasterRentalType : EntityBase, INotifyPropertyChanged 
{
    private string _RentalTypeId;
    private string _RentalTypeName;

    public string RentalTypeId
    {
        get { return _RentalTypeId; }
        set
        {
            _RentalTypeId = value;
            NotifyPropertyChanged("RentalTypeId");
        }
    }

    public string RentalTypeName
    {
        get { return _RentalTypeName; }
        set
        {
            _RentalTypeName = value;
            NotifyPropertyChanged("RentalTypeName");
        }
    }



    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}

The model class:

模型类:

public class MasterRentalModel: INotifyPropertyChanged 
{
    private MasterRentalType _SelectedMasterRentalType;
    private List<MasterRentalType> _MasterRentalTypeColl = new List<MasterRentalType>();

    public MasterRentalType SelectedMasterRentalType
    {
        get { return _SelectedMasterRentalType; }
        set
        {
            _SelectedMasterRentalType = value;
            NotifyPropertyChanged("SelectedMasterRentalType");
        }
    }

    public List<MasterRentalType> MasterRentalTypeColl
    {
        get { return _MasterRentalTypeColl; }
        set { _MasterRentalTypeColl = value; }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}

And in the code-behind, you just need to assign the model to the DataContextof you ComboBox; you can implement this any other function (here I have implemented it in the event handler of Loadedevent of my Window):

在代码隐藏中,您只需要将模型分配给DataContext您的 ComboBox;你可以实现这个任何其他功能(在这里我已经在事件处理程序实现了它Loaded我的情况下Window):

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        MasterRentalModel masterRentalModel = new MasterRentalModel();

        // Fill the list of RentalType here
        masterRentalModel.MasterRentalTypeColl.Add(new MasterRentalType() { RentalTypeId = "1", RentalTypeName = "Monthly" });
        masterRentalModel.MasterRentalTypeColl.Add(new MasterRentalType() { RentalTypeId = "2", RentalTypeName = "Quarterly" });
        masterRentalModel.MasterRentalTypeColl.Add(new MasterRentalType() { RentalTypeId = "1", RentalTypeName = "Yearly" });

        cb_rentaltype.DataContext = masterRentalModel;
    }

Whenever user changes the selection, SelectedMasterRentalTypewill be updated. And in the SelectedMasterRentalType, you can get both RentalTypeIdand RentalTypeName. If you follow proper binding your model will always be updated; that's the essence of WPF.

每当用户更改选择时,SelectedMasterRentalType都会更新。在 中SelectedMasterRentalType,您可以同时获得RentalTypeIdRentalTypeName。如果您遵循正确的绑定,您的模型将始终更新;这就是 WPF 的本质。

Hope this will help.

希望这会有所帮助。