What does exactly <Expander Header="{Binding}"> do? - c#

While creating a simple custom expander, I encountered the problem where items inside IT wouldn't bind. I found the fix on this link:
http://codeoverload.wordpress.com/2012/03/04/wpf-expander-headertemplates-dont-forget-the-binding/
Which happens to treat that exact same issue, however what I understand from it is "found this by luck, not really sure why it worked ;D"
My question being now: why does adding Header={Binding} fixes the issue. Indeed from the fact binding wouldn't work, it seems it's due to the DataContext, but I don't see how this should fix it.
Thanks for explaining; hopefully this isn't a duplicate >.<

From the docs
Gets or sets the data used for the header of each control.
That object being a binding against the DataContext, or plain text, or whatever.
I'd bet the implementation looks to see if the value is text, and if so, throws it into the default header template which could be something as simple as
<TextBlock Text="{Binding}" />
If you declare a template for the header, the DataContext will be whatever you assign to the Header property. The DataContext of the Expander doesn't flow automatically to the header template, apparently.

Related

Xamarin Forms TemplateSelector for View

I would like to use a TemplateSelector to select a View. Not for ListViewItems, like every example out there shows, but with a "normal" View. So i tried TemplatedView, ContentPresenter and ContentView. But non of them is able to take a TemplateSelector.
Is there something i have missed? Or how can i work around that?
EDIT:
I have a TemplateSelector, just like described here. Now i want to add this Selector to some kind of ViewElement. Thats what i tried:
<TemplatedView ControlTemplate="{StaticResource ViewItemTemplateSelector}"/>
or
<ContentPresenter Content="{StaticResource ViewItemTemplateSelector}"/>
But nothing works, it always says "Invalid resource type"
EDIT2:
<ResourceDictionary MergedWith="dataTemplates:DataTemplates">
<helper:ViewItemTemplateSelector x:Key="ViewItemTemplateSelector"
TextDataTemplate="{StaticResource TextDataTemplate}"/>
Have you tried following this guide of Xamarin?
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/templates/data-templates/selector/
Hope this works out for you.
EDIT:
Perhaps an alternative solution:
There are control templates but i don't think there is a selector for it. You could maybe use triggers for it? https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/triggers/#Data_Triggers not sure if this is way you looking

How to preview what a XAML control with bound values looks like

I'm writing an app in XAML, and I'm using binding for getting values to the UI layer. I'd like to see what my control will look like while making changes to the XAML, but because the data values are bound, many areas show up as blank (which, in turn, messes up the relative layout).
Is there any way to give XAML values to use for rendering the control review without replacing the Binding directives?
You can also use design time data to see how your xaml works. You just need to add new class that will be treated as design time view model. Its more elegant way to test xaml at design time.
Maybe you can set TargetNullValue or FallbackValue property in your binding, example:
<TextBlock Text="{Binding NotExsitOrNullPropertyName, TargetNullValue=SomeDefaultValue, FallbackValue=SomeDefaultValue}" ></TextBlock>
Hope it hepls.

Disable StackPanel Highlighting in XAML

I have found very little information about this matter. Know that I am a newbie to C# and WPF:
I have a stack panel defined in a XAML file as such :
<StackPanel Orientation="Vertical" >
<TextBlock Text="Locale: " VerticalAlignment="Center"/>
<ComboBox x:Name="comboLocale" Width="60" VerticalAlignment="Center" SelectionChanged="comboLocale_SelectionChanged"/>
</StackPanel>
I want to disable the highlighting that happens when I MouseOver the stack panel, which creates a blue color inside the StackPanel for some reason. I don't have any special style set up yet. Some threads talked about setting OverridesDefaultStyle to TRUE, but this didn't seem to change anything. Also, StackPanel do not have a ControlTemplate available, so most of the solutions I found couldn't be applied since they refer to a Button or TextBlock.
Any input on the matter would be greatly appreciated!
-Regards
StackPanels in general have no visual representation and are just layout containers which control placement of other elements. Given that you haven't set anything like Background on your StackPanel, it isn't what's causing the highlight you're seeing unless some other part of your XAML or code is modifying it. The behavior you describe sounds like the default behavior of a Button but without seeing more of your code it's hard to tell where the behavior is coming from.
Since you mentioned in a comment you've found out you're actually looking at the expected behavior of a Menu as your culprit. You'll just need to edit the MenuItem Control Template, more specifically the IsHighlighted that's causing your highlight. You'd likely find something like this helpful.
Or there's lots more various information found with a quick search for customizing a WPF Menu / MenuItem, hope this helps.

How can I prevent flickering when binding a boolean to the visibility of a control

I have a boolean property in my ViewModel, named lets say IsNotSupported that is used to show some warning information if a sensor is not supported. Therefore I use a BooleanToVisibilityConverter, that is added in the ressources:
<phone:PhoneApplicationPage.Resources>
<local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</phone:PhoneApplicationPage.Resources>
and bind it to the stackpanel containing the warning:
<StackPanel x:Name="NotSupportedWarning" Visibility="{Binding IsNotSupported,
Converter={StaticResource BooleanToVisibilityConverter}}">
That works all quite well, but when loading the page, and the sensor is supported, the warning appears for just a fraction of a second and disappears afterwards. I know that this flickering is caused by the binding not having happened yet and therefore defaulting to visible.
That flicker it is annoying as hell... It should rather default to collapsed and be made visible only after it is clear that the warning should be shown. Also, this would avoid a second layouting pass after the binding and could therefore have positive performance impacts.
I had this problem over and over, and found nothing about it in the internet until I found this SO question, that is closely related, but is not found if searched for windows phone instead of silverlight. Both the problem and the solution might seem simple, but I really bugged me quite a long time, so I thought it might be a good idea to write a Q&A-style question about it to help others that are facing the same issue.
The solution is simple after you have seen it. You can control the default value of the binding (if the binding didnt happen yet) with FallbackValue. Your stackpanel XAML would look like:
<StackPanel x:Name="NotSupportedWarning" Visibility="{Binding IsNotSupported,
FallbackValue=Collapsed,
Converter={StaticResource BooleanToVisibilityConverter}}">
This way you get rid of the flicker and it does not have to be relayouted after the binding, if the warning stays hidden.
you can bind directly to a Visibility type of property instead of boolean and keep that property to collapsed by default plus you can implement INotifyPropertyChanged

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.

Categories

Resources