简体   繁体   English

更改组合框应更新实体EF6

[英]Changing Combobox should update entity EF6

So basically, I have an entity, I've used a LINQ query to get some items and bound that to a combobox. 所以基本上,我有一个实体,我使用LINQ查询来获取一些项目并将其绑定到组合框。

What I'm trying to do is have the entity update when the item in the combobox is changed without doing a manual update in the Combobox.SelectedIndex/SelectedValue changed event. 我想要做的是更改组合框中的项目时,实体更新, 而无需在Combobox.SelectedIndex / SelectedValue更改事件中进行手动更新。 I'm just wondering if there is a better way? 我只是想知道是否有更好的方法?

Pseudo code: 伪代码:

SomeEntity se = new SomeEntity();
var q = from x in se select x;

cbComboBox.Datasource = q.ToList();
cbComboBox.DisplayMember = "SomeValue";
cbComboBox.ValueMember = "SomeValueID";
cbComboBox.SelectedValue = se.SomeValueID;

So the combobox shows the correct value I want. 因此,组合框显示了我想要的正确值。 That's fine. 没关系。

Here's the thing, when the user changes the combobox, I want se.SomeValueID to reflect that change. 事情就是这样,当用户更改组合框时,我希望se.SomeValueID反映该更改。

I know I can set se.SomeValueID in the combobox SelectedValue event, but is there a better way? 我知道可以在组合框SelectedValue事件中设置se.SomeValueID,但是有更好的方法吗? Where se.SomeValueID automagically gets updated? se.SomeValueID在哪里自动更新?

Assuming your question is about Windows Forms. 假设您的问题与Windows窗体有关。 To bind SelectedValue to an object's property you can add custom binding: 要将SelectedValue绑定到对象的属性,可以添加自定义绑定:

cbComboBox.DataBindings.Add("SelectedValue", se, "SomeValueID");

That binding is two-way and there's no need in cbComboBox.SelectedValue = se.SomeValueID; 该绑定是双向的,不需要cbComboBox.SelectedValue = se.SomeValueID; line. 线。

You should achieve this using Bindings defined in XAML instead of C# code behind code, here is an example: 您应该使用XAML中定义的绑定而不是代码后面的C#代码来实现此目的,这是一个示例:

 <ComboBox ItemsSource="{Binding SomeList}"
           DisplayMemberPath="SomeField"
           SelectedItem="{Binding CurrentItem, Mode=TwoWay}"/>

In this way you can have in your viewmodel class the list of entities (SomeList) and an object of the same type (CurrentItem) that will be updated every time the user change the selected item in the combobox. 这样,您可以在viewmodel类中具有实体列表(SomeList)和相同类型的对象(CurrentItem),每次用户在组合框中更改所选项目时,该列表都会更新。 If you don't need the entire object, you can bind the selected value to a property exposed on your viewmodel with the same time of the id. 如果不需要整个对象,可以将选定的值与ID相同的时间绑定到在视图模型上公开的属性。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM