I am failing in achieving a very sim开发者_C百科ple functionality from a WPF ComboBox.
My ComboBox needs to list a collection of values. This works fine. The value id is also saved succesfully in the database. The problem is that when i want to open the window in edit mode, the combo stays empty. Here is the code :
<ComboBox Height="28"
HorizontalContentAlignment="Center"
Name="cmbActivity"
ItemsSource="{Binding Path=Unit.UnitActivities}"
SelectedValuePath="Id"
SelectedValue="{Binding Path=UnitActivityId}"
Style="{StaticResource comboBoxInError}"
Width="200"
Margin="6"
HorizontalAlignment="Left">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock FlowDirection="LeftToRight" Text="{Binding Path=ActivityTime.Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.SelectedItem>
<Binding ElementName="cmbActivity" Path="UnitActivityId" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule />
<val:NotEmptyValidationRule />
<val:UnitResTimeOverlapValidationRule />
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
</ComboBox>
I understand my problem is somewhere in the SelectedItem section, but i just could not figure where and why.
Please help..
Thanks,
Try changing
<Binding ElementName="cmbActivity" Path="UnitActivityId" UpdateSourceTrigger="PropertyChanged">
to:
<Binding Path="UnitActivityId" UpdateSourceTrigger="PropertyChanged">
by removing the ElementName. It makes no sense to set the binding source to itself because the data context will infer this by default.
I am posting the answer for the original problem. This is idenctical to : WPF Cloned/Detached object edit problem - what is the standard?
First implement your cloneable object container :
public class ClonableObjectContainer : Object , ICloneable { private Object data; public ClonableObjectContainer(Object obj) { data = obj; } public Object Data { get { return data; } } public object Clone() { return (ClonableObjectContainer)this.MemberwiseClone(); } }
Then use this object with its Clone method to create your detached edit object:
ClonableObjectContainer coc = new ClonableObjectContainer(actor); EntityObject editEntity = (EntityObject)coc.Data;
After performing changes, detach the original object from the ObjectContext , attach the cloned object, change its state to
EntityState.Modified
and gracefully save:ContextManager.CurrentObjectContext.Detach(oldItem); ContextManager.CurrentObjectContext.Attach((IEntityWithKey)item); ContextManager.CurrentObjectContext.ObjectStateManager.ChangeObjectState(item, EntityState.Modified); ContextManager.Save();
Hope it helps... Oran
精彩评论