Unbound combobox doesn't show value - c#

hope you can help me, there are a lot of posts on this topic, but none matches my problem really.
I've got a WPF-Window with unbound text- and comboboxes. They're filled in a foreach-loop on load programmatically by c# code with values from an Xml-database.
switch (TypeOfSync)
{
case SyncType.FromXmlDataBase:
MyControl.Text = MyXmlSubNode.InnerText;
break;
case SyncType.ToXmlDataBase:
MyXmlSubNode.InnerText = MyControl.Text;
break;
default:
break;
}
The target combobox may not be editable.
<ComboBox x:Name="OPReason">
<ComboBoxItem Content=""/>
<ComboBoxItem Content="Erstimplantation"/>
<ComboBoxItem Content="Revision bis 3 Monate"/>
<ComboBoxItem Content="Revision"/>
</ComboBox>
In all other comboboxes everything works well. Also in this box everything is ok, until the the code sets the text property to "Revision". Then nothing is displayed, even if return value of the text property shows the correct value.
Of course you will say now, choose a databinding approach, but other actions have to performed simultaneously, so this is not really an option. A bit misterious. Might the similar beginning of "Revision" and "Revision bis 3 Monate" be the problem??

Filling text- and comboboxes manually by code from an XmlDatabases seems to be an susceptible way. Using databindings with a viewmodel is much safer and more reliable.

Related

Xceed CheckComboBox not properly showing selected values from items hardcoded in XAML

I try to use a CheckComboBox control from the Xceed library.
When I select an item, the control displays system.windows.controls.comboxitem:"value" instead of just value
Is there a way to display only the value of the selected item without its type?
<xctk:CheckComboBox>
<ComboBoxItem Content="SA" />
<ComboBoxItem Content="NA" />
</xctk:CheckComboBox>
In this particular case it can be solved by adding the DisplayMemberPath="Content"
<xctk:CheckComboBox DisplayMemberPath="Content">
<ComboBoxItem Content="SA"/>
<ComboBoxItem Content="NA"/>
</xctk:CheckComboBox>
But whether it is a designed feature or just a serendipitous behaviour, I am not sure.
So overall it would be better in the future to read on WPF binding, and use datasources and bindings to make the code similar to what is on the documentation page.
<xctk:CheckComboBox
DisplayMemberPath="Color"
ValueMemberPath="Level"
SelectedValue="{Binding SelectedValue}"
SelectedItems="{Binding SelectedItems}" />

WPF change selected value in one ComboBox by another ComboBox in MVVM

I am having a problem. I have two combobox in WPF first:
<ComboBox commands:PropertyChangeBehavior.Command="{Binding GetCurrentsModuleCommand}" SelectedIndex="0">
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem IsEnabled="True">All</ComboBoxItem>
<CollectionContainer Collection="{Binding Source={StaticResource ResourceKey=AxmModulesCombo}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
</StackPanel>
Lets call it Source and it is binded to command:
public ICommand GetCurrentsModuleCommand => new Command(module =>
{
SelectedAxmModule = module.ToString();
Stuff(module);
});
And this combo box has no SelectItem property (well it don't needs any as parameters are only pass to method).
And a Target CombxBox
<ComboBox ItemsSource="{Binding AxmModules}"
SelectedItem="{Binding SelectedAxmModule, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValuePath="{Binding SelectedAxmModules}"
IsSynchronizedWithCurrentItem="True"/>
Witch SelectedItem property is binded to:
private string selectedAxmModule;
public string SelectedAxmModule
{
get => selectedAxmModule;
set
{
selectedAxmModule = value;
OnPropertyChanged();
}
}
Now those combo boxes are similar in values, now I want to do if I click value on source as you see in source command i want to select same value from source (I handled values from source and not in target in code so that is irrelevant).
I tried adding Update property and SelectedValuePath but no good value in target combo box is still empty after selecting value from source, and OnPropertyChange works as inteded. Is there a way to achieve this?
If AxmModules is an IEnumerable<byte>, SelectedAxmModule should be a byte property. You cannot set a string property to a byte value. The types must match.
And SelectedValuePath is superfluous when using SelectedItem.
Since you have
IsSynchronizedWithCurrentItem="True"/>
Then the selecteditem should be the current. You should work with the current item of the collectionview rather than binding selecteditem.
You can read more, probably more than you want to read, about collectionview and this sort of stuff here:
https://social.technet.microsoft.com/wiki/contents/articles/26673.wpf-collectionview-tips.aspx
Also.
See this
SelectedValuePath="{Binding SelectedAxmModules}"
The selectedvaluepath is a string not a binding. It should be the name of whichever field you want to use.
If, for whatever reason, you want to bind to the current item in a collection then you can use the / notation.
https://social.technet.microsoft.com/wiki/contents/articles/29859.wpf-tips-bind-to-current-item-of-collection.aspx
I'm not sure how this is going to fit with a composite collection though. I prefer a separate control to indicate selection of "all" and hence wouldn't use a composite collection in this way. You might want to consider that approach yourself.

WPF TextBox with both static and editable text?

I have a data entry application, with (among other things) a textbox for recording comments. These comments are specific to the data being entered, and often times are redundant (same comment given for a range of data records).
I'm planning to add a combobox with a canned selection of comments to cover the most common situations. When one is selected from the combobox, the comment textbox is populated with the canned comment.
However, I also need the ability to enter additional comments after the canned message, within the textbox. But I don't want it to be possible for the canned message to be altered. All entered comments need to come after the canned comment.
Is there a way to apply static text to a textbox which cannot be altered, but still allow text to be entered below it?
The only idea I've come up with so far is to catch TextInput events and continually overwrite the beginning of the textbox content with the canned message, but the result wouldn't exactly be pretty.
You could just place a disabled TextBox immediately above the editable TextBox and remove their bottom and top borders respectively so that they look like one big TextBox.
Perhaps overwrite a TextBox template so that it contains a Panel with the Canned Message ComboBox and a regular TextBox for user input.
Style the inner TextBox so it doesn't have the regular TextBox border, and style the ComboBox so that when it doesn't have focus it doesn't show it's border either.
When the ComboBox has focus, it will look like a ComboBox inside a TextBox, and if it doesn't have focus it will just look like one big TextBox
No, as much I aware of , you can not have something like this. But you can:
Have a label on top (side) of it with static text applied
If you have enough space, have a readonlt text box for preview of the comment, more or less like SO comment editor works.
You can try to not let to delete several count of characters from binded data ( which will be actually static text)
Hope this helps.
I would adopt a slightly different strategy.
If something has been selected in the Combobox, then concatenate the input in the selected combo-box item text and the textbox text. If not, use the textbox text.
Of course you could use the selected event of the combobox to chnage the label to reflect the change in circumstance.
I think you can bind the textBox1.Text with the combobox selected item as Oneway mode. The following is code snipet
<ComboBox Height="23" HorizontalAlignment="Left" Margin="118,48,0,0" Name="comboBox1" VerticalAlignment="Top" Width="144">
<ComboBoxItem Content="Commanet 1" />
<ComboBoxItem Content="Comment 2" />
</ComboBox>
<TextBox Height="64" HorizontalAlignment="Left" Margin="118,101,0,0" Name="textBox1" VerticalAlignment="Top" Width="144" Text="{Binding ElementName=comboBox1, Path=SelectedItem.Content, Mode=OneWay}" />
2 more options.
Override the style of the textbox to include the fixed text - pass the fixed text though some templatebinding
You can capture the PreviewKey<> events on the textbox and cancel it its modifying the "fixed" text, and if not let the event go through.
But 2 textboxes that visually look as 1 is still a better option though - easiest to implement and maintain

WPF Combobox binding: can't change selection

After wasting hours on this, following on the heels of my Last Problem, I'm starting to feel that Framework 4 is a master of subtle evil, or my PC is haunted.
I have three comboboxes and a textbox on a WPF form, and I have an out-of-the-box Subsonic 3 ActiveRecord DAL.
When I load this "edit record" form, the comboboxes fill correctly, they select the correct items, and the textbox has the correct text. I can change the TextBox text and save the record just fine, but the comboboxes CANNOT BE CHANGED. The lists drop down and highlight, but when you click on an item, the item selected stays the same.
Here's my XAML:
<StackPanel Orientation="Horizontal" Margin="10,10,0,0">
<TextBlock Width="80">Asset</TextBlock>
<ComboBox Name="cboAsset" Width="180"
DisplayMemberPath="AssetName"
SelectedValuePath="AssetID"
SelectedValue="{Binding AssetID}" ></ComboBox>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10,10,0,0">
<TextBlock Width="80">Status</TextBlock>
<ComboBox Name="cboStatus" Width="180"
DisplayMemberPath="JobStatusDesc" SelectedValuePath="JobStatusID"
SelectedValue="{Binding JobStatusID}" ></ComboBox>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10,10,0,0">
<TextBlock Width="80">Category</TextBlock>
<ComboBox Name="cboCategories" Width="180"
DisplayMemberPath="CategoryName"
SelectedValuePath="JobCategoryID"
SelectedValue="{Binding JobCategoryID}" ></ComboBox>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10,10,0,0">
<TextBlock Width="80">Reason</TextBlock>
<TextBox Name="txtReason" Width="380" Text="{Binding Reason}"/>
</StackPanel>
Here are the relevant snips of my code (intJobID is passed in):
SvcMgrDAL.Job oJob;
IQueryable<SvcMgrDAL.JobCategory> oCategories = SvcMgrDAL.JobCategory.All().OrderBy(x => x.CategoryName);
IQueryable<SvcMgrDAL.Asset> oAssets = SvcMgrDAL.Asset.All().OrderBy(x => x.AssetName);
IQueryable<SvcMgrDAL.JobStatus> oStatus = SvcMgrDAL.JobStatus.All();
cboCategories.ItemsSource = oCategories;
cboStatus.ItemsSource = oStatus;
cboAsset.ItemsSource = oAssets;
this.JobID = intJobID;
oJob = SvcMgrDAL.Job.SingleOrDefault(x => x.JobID == intJobID);
this.DataContext = oJob;
Things I've tried:
Explicitly setting IsReadOnly="false" and IsSynchronizedWithCurrentItem="True"
Changing the combobox ItemSources from IQueryables to Lists.
Building my own Job object (plain vanilla entity class using INotifyPropertyChanged).
Every binding mode for the comboboxes.
ItemsSource="{Binding}"
The Subsonic DAL doesn't implement INotifyPropertyChanged, but I don't see as it'd need to for simple binding like this. I just want to be able to pick something from the dropdown and save it.
Comparing it with my last problem (link at the top of this message), I seem to have something really wierd with data sources going on. Maybe it's a Subsonic thing?
EDIT: For some reason the set accessor is hit only on the AssetID property and only the first time. WPF is now heading for WTF :)
EDIT 2: You gotta be kidding me- I've removed the binding (ie it only has a displaymemberpath, a valuememberpath and an itemssouce) and it's STILL doing it! It accepts your first selection, and then won't change.
WPF Combo Boxes will not change the selected item if the currently selected item and the item that was just selected are considered equal by the object.Equals() method called on the newly selected object (i.e newlyslected.Equals(previoslySelected) ).
Overriding the Equals method on the class your binding the combobox items, should resolve the issue your are seeing.
I've narrowed it down to the Subsonic objects used as ComboBoxItems.
If you create a new class that uses exactly the same code as the relevant parts of the Subsonic one, it works.
If you use POCOs/datatables for the combos and Subsonic for the record being edited, it works.
But if you use Subsonic for both, it doesn't.
I had hoped to extend the subsonic objects and not have to code a full-blown BLL tier. Looks like I'm faced with doing that or throwing out Subsonic for the DAL. I might post a more specific question for the Subsonic folks.
Many thanks to all who contributed.
Old topic but I had the same problem and difficulty finding solution. This might help someone else.
Clue is above in WPF not detecting a different item has been seleted by user. (Symptom - event ComboBox_SelectionChanged only fires on first selection)
My scenario - lookup combo populated from IList built from a DISTINCT query. In this case the result of using NHibernate ICriteria.SetResultTransformer which only returns SOME fields, importantly NOT including the unique entity ID.
Solution - loop thru' IList after retrieval and give each entity a unique ID. WPF sees them as individuals and behaves appropriately.
Its only a value lookup - its the value content I was after.
The 'temporary' entities are never persisted. In this case it was a better approach than messing with overriding the object's Equals method for the sake of a simple GUI issue. An alternative would be to just copy or tranform the list into a format where WPF uses the value field to determine 'difference'...
Sounds like the field is somehow readonly, or that your change isn't being persisted. After the binding sets the new value, it will re-read the property to ensure that it was actually changed. If your property returns the old value, then it'll be re-selected in the combo box, giving the appearance that the value never changed.
I don't know that DAL, but can you step through the property setter code? You might also have an issue with type conversion.
EDIT reading your comment about the red rectangle -- it sounds as though your property (or something to do with the binding) is raising an exception. Unless, of course, you're using data validation in your UI. You might turn 'Break on all exceptions' in the debugger's settings, assuming you're using Visual Studio.
EDIT 2 You should check the VS Output pane for any error messages related to binding. You can also read this blog post which gives more info on debugging bindings.
It's hard to tell from a small sample of your code but try commenting out the line:
//this.DataContext = oJob;
and see if this helps.
Setting the DataContext and ItemsSource might be causing a conflict.
Did you write any global style for your combo box which may have a bug or something missing? Or are you using pure default styles for your combobox? Try removing any default styles applied.
Are you wiring up any events? If your code hooks up for event like PreviewMouseLeftButtonUp and marks event as handled then probably combobox may ignore and wont select anything.

Adding ComboBoxItem to ComboBox Issue in Silverlight 4

I recently upgraded my Silverlight app from 3 to 4. After a few hours of bashing my head against the wall, trying to resolve an issue, I've narrowed down the problem to this:
I have a user control, with a ComboBox inside it. The ComboBox has a single ComboBoxItem child. The user control exposes a get accessors that returns the ComboBox's Items object, allowing me to add additional ComboBoxItems via xaml.
This all worked fine in Silverlight 3, however it's not working in Silverlight 4.
As code:
//XAML
<UserControl ... >
<ComboBox Name="myComboBox">
<ComboBoxItem Content="Select an Item" />
</ComboBox>
<!-- All my other stuff -->
</UserControl>
//Code behind
public ItemCollection ListItems
{
get
{
return myComboBox.Items;
}
}
//Implementation of User-Control
<CustomControl:UserControl ... >
<CustomControl:UserControl.ListItems>
<ComboBoxItem Content="Item 1" />
<ComboBoxItem Content="Item 2" />
<ComboBoxItem Content="Item 3" />
</CustomControl:UserControl.ListItems>
</CustomControl:UserControl>
As I mentioned, this all worked fine in Silverlight 3, but doesn't work in Silverlight 4.
The workaround, it seems, is to remove that single ComboBoxItem that's inside my user-control, but I'm hoping to avoid, as I want it as the default item.
Any help would be much appreciated!
The XAML parser was re-written for Silverlight 4 to make it more consistent with WPF. I am pretty certain the behavior you are expecting was a bug in SL3 and I don't think it would have worked that way in WPF though I've never actually tried.
You may be able to get the old mode back by enabling quirks mode but I wouldn't recommend it. Instead, what I would do is create a ControlTemplate for the combo box to display the "select an item" text when there is nothing selected. Having that be an actual item in the combo box really just a hack that we've always been forced to do with technologies such as Windows Forms and HTML but in Silverlight it seems like having SelectedItem be null is more appropriate.

Categories

Resources