Binding problem in DataTemplate with custom Control - get

I have a DataGrid which binds an ObservableCollection. The DataContext of MainWindow is set to MainWindowViewModel and this contains the ObservableCollection for the DataGrid.
In the DataGrid i have a DataTemplate. When i bind the Collection to a standard control lika a Label, the databinding works fine, but when i used a custom control, the databinding does not work.
My XAML:
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
...
<DataGrid ItemsSource="{Binding ShiftTimes, Mode= TwoWay, UpdateSourceTrigger=PropertyChanged ....}">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataTemplate>
<cControls:MyUserControl SelectedTime="{Binding Path=From}" /> <-- DOES NOT WORK
<Label Content="{Binding Path=From}"/> <-- Works fine
</DataTemplate>
</DataGridTemplateColumn>
</DataGrid.Colums>
</DataGrid>
My control is a XAML-ControlTemplate and the the specific property "SelectedTime" is set by
...
<StackPanel DataContext = "{Binding Path=SelectedTime, RelativeSource={RelativeSource Mode=FindAnchestor, AnchestorType=local:MyUserControl}}>
...
the "SelectedTime"-Property is a DependencyProperty
the code behind my UserControl:
public TimeSpan SelectedTime
{
get { return (TimeSpan)GetValue(SelectedTimeProperty); }
set { SetValue(SelectedTimeProperty, value); }
}
public static readonly DependencyProperty SelectedTimeProperty =
DependencyProperty.Register("SelectedTime",typeof(TimeSpan),
typeof(MyUserControl),
new FrameworkPropertyMetadata(MyUserControl.MinValidTime, new PropertyChangedCallback(MyUserControl.OnSelectedTimeChanged), new CoerceValueCallback(MyUserControl.CoerceSelectedTime)));
the debugger gives the following output:
System.Windows.Data Warning: 67 : BindingExpression (hash=14315403): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=14315403): Found data context element: MyUserControl (hash=1590600) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=14315403): Activate with root item ShiftTime (hash=53855148)
System.Windows.Data Warning: 108 : BindingExpression (hash=14315403): At level 0 - for ShiftTime.From found accessor ReflectPropertyDescriptor(From)
System.Windows.Data Warning: 104 : BindingExpression (hash=14315403): Replace item at level 0 with ShiftTime (hash=53855148), using accessor ReflectPropertyDescriptor(From)
System.Windows.Data Warning: 101 : BindingExpression (hash=14315403): GetValue at level 0 from ShiftTime (hash=53855148) using ReflectPropertyDescriptor(From): TimeSpan (hash=0)
System.Windows.Data Warning: 80 : BindingExpression (hash=14315403): TransferValue - got raw value TimeSpan (hash=0)
System.Windows.Data Warning: 89 : BindingExpression (hash=14315403): TransferValue - using final value TimeSpan (hash=0)
Thanks for Your help
UPDATE:
I found the reason. In my Control-Constructor i set the SelectedTime-Property explicit to a value.
After deleting this, the binding works.
In this thread -> https://stackoverflow.com/a/66698078
i read, "Detachment bahavior usually occurs when a value set outside of the data-binding" and that is the answer of my problem.
this thread can also be closed.

Related

Triggering function on Xamarin.Forms Entry Focused/Unfocused

Original problem: I want to call a function each time the soft keyboard is shown/hidden on my Xamarin.Forms ContentPage.
One option was to use a custom renderer where I have access to the keyboard observers. I haven't tried this yet; I thought I'd try banging my head with other approaches first.
Approach 1) Assign event handler to the Focused/Unfocused events of all entries on my page which trigger a keyboard show/hide, in the page's code-behind as follows:
EventHandler<FocusEventArgs> keyboard_handler = (object sender, FocusEventArgs e) =>
{
var binding_context = BindingContext as MyViewModel;
binding_context?.OnKeyboardShowing();
};
PasswordEntry.Focused += keyboard_handler; // doesn't trigger keyboard_handler
PasswordEntry.Unfocused += keyboard_handler; // doesn't trigger
UsernameEntry.Focused += keyboard_handler; // triggers
UsernameEntry.Unfocused += keyboard_handler; //doesn't trigger
Question 1: Why don't some of those trigger?
Approach 2) Use EventTriggers along with a custom TriggerAction<Entry> class, as follows:
Part of the XAML file showing one of the entries (which is in a grid, in a StackLayout in a ScrollView in a Grid, if you must know):
<Entry Grid.Row="0"
x:Name="UsernameEntry"
Margin="0,2"
HorizontalOptions="FillAndExpand"
Placeholder="User"
IsVisible="{Binding UsernameEnabled}"
Completed="Username_Completed"
IsEnabled="{Binding EnableControls}"
Text="{Binding Username, Mode=TwoWay}" >
<Entry.Triggers>
<EventTrigger Event="Focused">
<local:FocusedAction />
</EventTrigger>
</Entry.Triggers>
</Entry>
And the TriggerAction<Entry> class defined in the code-behind:
public class FocusedAction : TriggerAction<Entry>
{
protected override void Invoke(Entry entry)
{
Debug.WriteLine("Reached"); // Except it never reaches here.
}
}
Question 2: Why doesn't Invoke up there ever get triggered?
Am I missing something in my XAML, code-behind or somewhere else? I've checked the Xamarin docs, but as always, I've found them less than useless.

Set Default value in <p:autoComplete>

iam using primefaces autocomplete and it works fine but if iam setting default value it gives me an error.
here is my Xhtml code:
<p:autoComplete id="parametername" required="true"
requiredMessage="Parameter Name can't be blank"
maxResults="5"
value="#{manageAppParaValuesTO.appParameterValuesBean.parameterName}"
tabindex="1" forceSelection="true"
styleClass="select-area-150 CommoninputText input_text_style1" cache="enabled"
dropdown="true"
completeMethod="#{manageAppParaValuesTO.completeDropDownParameter}"
disabled="#{manageAppParaValuesTO.deleteFlag or manageAppParaValuesTO.viewFlag or manageAppParaValuesTO.editFlag}"
var="field" itemValue="#{field.parameterName}"
itemLabel="#{field.parameterName}">
and here is java code:
public List<ApplicationParameterValuesEntityTO> completeDropDownParameter(
String like) {
System.out.println("-----------------> completeParameter ");
newAppParameterNameDropDown = new ArrayList<ApplicationParameterValuesEntityTO>();
for(ApplicationParameterValuesEntityTO appValueEntity : appParameterNameDropDown){
System.out.println(" Like "+like+"-------> appValueEntity.getParameterName "+appValueEntity.getParameterName());
if(appValueEntity.getParameterName().toUpperCase().matches(like+".*") || appValueEntity.getParameterName().toLowerCase() .matches(like+".*")){
System.out.println("-------->"+appValueEntity.getParameterName());
newAppParameterNameDropDown.add(appValueEntity);
}
}
return newAppParameterNameDropDown;
}
if manageAppParaValuesTO.appParameterValuesBean.parameterName already have value then the following error is encountered:
javax.el.PropertyNotFoundException: itemLabel="#{field.parameterName}": Property 'parameterName' not found on type java.lang.String

WinRT Event Handling from DataTemplate

I have a DataTemplate which requires an event handler for one of the objects. This DataTemplate is contained in a ResourceDictionary. What is the best way to add an event handler to this template?
I tried defining the event handler in app.xaml.cs but the handler isn't executing. Creating a code behind file for the ResourceDictionary leads to load errors during app start up in MergedDictionaries.
from GraphStyles.xaml
<DataTemplate x:Key="PieTemplate">
<Grid HorizontalAlignment="Left" Width="350" Height="350" >
<Border>
<Charting:Chart
x:Name="PieChart"
Title="Play Attempts"
Margin="70,0" Loaded="PieChart_Loaded">
<Charting:Chart.Series>
<Charting:PieSeries
Title="Attempts"
ItemsSource="{Binding Items}"
IndependentValueBinding="{Binding Name}"
DependentValueBinding="{Binding Value}"
IsSelectionEnabled="True" />
</Charting:Chart.Series>
</Charting:Chart>
</Border>
</Grid>
</DataTemplate>
in App.Xaml.cs
private void PieChart_Loaded(object sender, RoutedEventArgs e)
{
var pieChart = sender as Chart;
var legendItems = ((PieSeries)pieChart.Series[0]).LegendItems;
foreach (LegendItem item in legendItems)
{
pieChart.LegendItems.Add(item);
pieChart.LegendStyle = item.Style;
}
}
Option 1
As far as I am aware you will have to reference the datatemplate in the page/usercontrol's Resources at the top. Use a merged dictionary so you can still utilize the graphstyles.xaml.
If you are uncomfortable as this breaks your convention, there is a rather long winded alternative:
Option 2
Use an MVVM Viewmodel and set the page/usercontrols DataContext.
Keep the datatemplate in the graphstyles.xaml and use an Attached Behavior to hook the Loaded event, passing the event trigger up to the viewmodels command.
Create an event in the ViewModel that the UI can respond to, then hook onto that and handle in the Views codebehind as you have done.
I must say I'm not mad on Option 2 as it kind of breaks some view/VM seperation but it should get the job done - note that you will have to pass the chart as an object through from the attached behavior, to the viewmodel then back to the view against before you cast it back to a Chart.

java.lang.IllegalArgumentException: Component javax.faces.component.html.HtmlDataTable is no org.apache.myfaces.custom.datalist.HtmlDataList

In my JSF application I am using data table & data list from tomhawk`s implementation as well as but sometimes I get following exception. This happens only when I am using Chrome browser only.
java.lang.IllegalArgumentException: Component javax.faces.component.html.HtmlDataTable is no org.apache.myfaces.custom.datalist.HtmlDataList
org.apache.myfaces.custom.datalist.HtmlDataListTag.setProperties(HtmlDataListTag.java:117)
javax.faces.webapp.UIComponentTag.createComponent(UIComponentTag.java:209)
javax.faces.webapp.UIComponentClassicTagBase.createChild(UIComponentClassicTagBase.java:476)
javax.faces.webapp.UIComponentClassicTagBase.findComponent(UIComponentClassicTagBase.java:660)
javax.faces.webapp.UIComponentClassicTagBase.doStartTag(UIComponentClassicTagBase.java:1126)
org.apache.jsp.HomeV_jsp._jspx_meth_t_005fdataList_005f0(HomeV_jsp.java:3903)
org.apache.jsp.HomeV_jsp._jspx_meth_h_005fform_005f1(HomeV_jsp.java:3861)
org.apache.jsp.HomeV_jsp._jspx_meth_f_005fview_005f0(HomeV_jsp.java:450)
org.apache.jsp.HomeV_jsp._jspService(HomeV_jsp.java:155)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:408)
com.sun.faces.application.ViewHandlerImpl.executePageToBuildView(ViewHandlerImpl.java:442)
com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:115)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106)
com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:696)
org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:667)
org.apache.jsp.index_jsp._jspService(index_jsp.java:67)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
com.advernture.discountbox.security.PageFilter.doFilter(PageFilter.java:43)
Does anyone has any clue about what might be happening here?
The code which causes this is as follows:
<h:form id="browse_by_categry_frm">
<div id="tagcloud">
<t:dataList id="offer_cloud_table" value="#{CityCatagoryB.ctgryLstAsStr}" var="cat" binding="#{FindB.data}" layout="simple">
<span style="padding-left:10px;padding-right:10px">
<h:commandLink value="#{cat}" action="#{FindB.doFind}" styleClass="subMenu"/>
</span>
</t:dataList>
</div>
</h:form>
The binding="#{FindB.data}" should refer to a property which is used by only one component. This exception indicates that the bean is session scoped and that you're sharing the same binding="#{FindB.data}" on a <h:dataTable> component somewhere else in the webapp. That it occurs in Chrome only is probably because it was the only browser where you have opened the other page with <h:dataTable> in the same session beforehand.
Make sure that you don't share the property behind binding among multiple components. Otherwise your bean has really to be in the request scope. Or, look for a way to get rid of binding, perhaps by making the value a DataModel.
Looks like a binding problem. In your FindB bean you have
private HtmlDataTable data;
//getters/setters
But you should have:
private HtmlDataListdata;
//getters/setters
instead. Because t:dataList has to be bound to a reference of type org.apache.myfaces.custom.datalist.HtmlDataList.
kindly when you are set your list as the following:
/**
* Setter Related Report Link Roles.
*
* #param relatedReportLinkRoles: Related Report Link Roles.
*/
public void setRelatedReportLinkRoles(List relatedReportLinkRoles) {
this.relatedReportLinkRoles = relatedReportLinkRoles;
}
instead of that you must use the following:
/**
* Setter Related Report Link Roles.
*
* #param relatedReportLinkRoles: Related Report Link Roles.
*/
public void setRelatedReportLinkRoles(List relatedReportLinkRoles) {
this.relatedReportLinkRoles = relatedReportLinkRoles;
if(roleRelatedReportDataTable != null) {
roleRelatedReportDataTable.setValue(relatedReportLinkRoles);
}
}

Problem displaying custom property values for SharePoint custom field types

I'm trying to create a custom field type in SharePoint (WSS 3.0) that has custom properties. I have created my fldtypes*.xml file based on the SDK docs and this blog post and it seems to render fine and I can retrieve the custom property values inside my code. My problem is that after the initial field creation, if I go back to the list settings page and click on my newly added field, the form shows my custom properties with some value that I'm not providing it. For example, if my custom property's display name is "My Custom Prop" then the value in its textbox will be "My Custom Prop field value".
My question is this: how can I properly show the actual string values of my custom property types in these textboxes?
Here's my fldtypes*.xml file:
<?xml version="1.0" encoding="utf-8"?>
<FieldTypes>
<FieldType>
<Field Name="TypeName">MyCustomField</Field>
<Field Name="TypeDisplayName">My Custom Field</Field>
<Field Name="TypeShortDescription">MyCustomField</Field>
<Field Name="ParentType">Text</Field>
<Field Name="UserCreatable">TRUE</Field>
<Field Name="FieldTypeClass">MyCustomField.CustomFields.MyCustomField, MyCustomField, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d772gbab82fe6996</Field>
<PropertySchema>
<Fields>
<Field Name="MyCustomProp" DisplayName="My Custom Prop" Type="Text" MaxLength="50" DisplaySize="30" />
</Fields>
</PropertySchema>
</FieldType>
</FieldTypes>
And here's the code for my field type class:
public class MyCustomField : SPFieldText
{
private string propval;
public MyCustomField(SPFieldCollection fields, string fieldName)
: base(fields, fieldName)
{
}
public MyCustomField(SPFieldCollection fields, string typeName, string displayName)
: base(fields, typeName, displayName)
{
}
public override void Update()
{
// I can see any updated value here
propval = GetCustomProperty("MyCustomProp") as string;
base.Update();
}
public override Type FieldValueType
{
get { return typeof (string); }
}
}
What can I do to see the correct custom property values in my "Change Column" page (FldEditEx.aspx) in my SharePoint app?
There is a well known issue with saving and retrieving custom properties on a custom field type. Here is a direct link to the work around.
btw, some of the comments on the post purport the same problem.

Resources