I have tried my textfield to have the very first letter to be capitalized with the following code :-
Form f = new Form();
TextField firstname = new TextField();
firstname.setConstraint(TextField.INITIAL_CAPS_SENTENCE);
f.addComponent(firstname);
f.show();
But this is not working.
What am I missing here? Can anybody suggest a correct way to achieve it?
Note : I am using LWUIT 1.5
Edited
This is how I finally did it with the help of Shai
public void insertChars(String c) {
super.insertChars(c); //To change body of generated methods, choose Tools | Templates.
if(super.getText()!=null && super.getText().length()>0){
super.setText((super.getText().substring(0,1).toUpperCase())+super.getText().substring(1, super.getText().length()));
}else{
super.setText(super.getText());
}
}
Are you using a qwerty J2ME device by any chance? If so this won't work since this only applies to the native side of the things.
You need to derive TextField and override insertChar() to implement this.
Related
So I am working with SQLite, CommunityToolkit.Mvvm.ComponentModel;
I have database containing a table of friends. I can bind this to a CollectionView.
I am following https://www.youtube.com/watch?v=8_cqUvriwM8 but trying to use MVVM approach.
I can get it to work happily with SelectionChanged and an event, but not with SelectionChangedCommand and I can't get access to the Friend item in the list.
Here is the relevant xaml
<CollectionView Grid.Row="2"
x:Name="FriendsList"
SelectionMode="Single"
SelectionChangedCommand="{Binding SelectionChangedCommand}"
SelectionChangedCommandParameter="{Binding .}"
SelectionChanged="OnSelectionChanged" >
Here is the relevant part of the code (I'm using the code behind for the xaml just for testing)
public MainPage()
{
InitializeComponent();
this.BindingContext = this; //cool for binding the xaml to the code behind.
}
...
//This works fine (so why do I bother with mvvm?)
public void OnSelectionChanged(Object sender, SelectionChangedEventArgs e)
{
Console.WriteLine("Selection changed click");
Friend f = e.CurrentSelection[0] as Friend;
Console.WriteLine(f.LName);
}
//Can't get this to work, though it will register the click
public ICommand SelectionChangedCommand => new Command(SelectionChangedControl);
public void SelectionChangedControl()
{
Console.WriteLine("selection made");
}
My thinking was that if I could do this to get at the Friend item since the CommandParameter is, as I understand, to provide an object?
public ICommand SelectionChangedCommand => new Command<Friend>(SelectionChangedControl);
public void SelectionChangedControl(Friend f)
{
Console.WriteLine("selection made");
}
But the command doesn't even fire now. Clearly I am way off beam.
Any ideas please. (Oh by the way I have tried commenting out one or the other just in case).
BTW is there a reference (not MS docs) which explains this stuff in beginners terms?
Is there an API reference to dot net Maui?
EDIT: From the documentation https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/collectionview/selection
Single selection
When the SelectionMode property is set to Single, a single item in the CollectionView can be selected. When an item is selected, the SelectedItem property will be set to the value of the selected item. When this property changes, the SelectionChangedCommand is executed (with the value of the SelectionChangedCommandParameter being passed to the ICommand, and the SelectionChanged event fires.
How do I get at value of the SelectionChangedCommandParameter, i.e. the row object, i.e. my Friend object?
EDIT2: Somehow I think I need to get at the CurrentSelection[0] but I don't know how.
I've learnt that I can do something like this (from the docs)
SelectionChangedCommand="{Binding SelectionChangedCommand}"
SelectionChangedCommandParameter="Hello G"
and
public ICommand SelectionChangedCommand => new Command<string>( (String s) =>
{
Console.WriteLine($"selection made {s}");
});
and the command is picked up and displayed, so my thinking is that using {Binding .} is not what I want, but what do I bind to?
SelectionChangedCommandParameter ={Binding ???}
Thanks, G.
first, bind SelectedItem
SelectedItem="{Binding SelectedFriend}"
then in your VM create a property for that bound item
public Friend SelectedFriend { get; set; }
then in your Command you can use that property
public void SelectionChangedControl()
{
Console.WriteLine(SelectedFriend.Name);
}
When you use . at CollectionView.SelectionChangedCommandParameter, it points at the BidingContext of its parent view.
e.g. If your CollectionView is in a ContentPage, . points at the BindingContext of the ContentPage.
If you want a reference of each item in FriendsList, one of solutions is use SelectedItem.
Try something like this:
<CollectionView
Grid.Row="2"
x:Name="FriendsList"
SelectionMode="Single"
SelectionChangedCommand="{Binding SelectionChangedCommand}"
SelectionChangedCommandParameter="{Binding Path=SelectedItem, Source={x:Reference FriendsList}}">
or
<CollectionView
Grid.Row="2"
SelectionMode="Single"
SelectionChangedCommand="{Binding SelectionChangedCommand}"
SelectionChangedCommandParameter="{Binding Path=SelectedItem, Source={RelativeSource Self}}">
References:
Bind to self (Source={RelativeSource Self}}):
https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/relative-bindings#bind-to-self
Note for Multiple Selections
I got hung up trying to bind multiple selections to the view model without linking it in the code behind. This page was the only relevant search result and helped a lot, but was missing a piece for multiple selections.
View.xaml
<CollectionView ItemsSource="{Binding DataItems}"
SelectedItems="{Binding SelectedData}"
SelectionMode="Multiple"
SelectionChangedCommand="{Binding SelectionChangedCommand}">
....
Couple of things to mention for the view model. I'm using CommunityToolkit.Mvvm, so the [ObservableProperty] annotation creates the property for you in proper camel case, and the [RelayCommand] for OnMethodName will drop the 'On' and just be MethodNameCommand.
ViewModel.cs
[ObservableProperty]
ObservableCollection<CustomDataItem> dataItems;
[ObservableProperty]
ObservableCollection<object> selectedData;
[RelayCommand]
void OnSelectionChanged()
{
foreach(var o in SelectedData)
{
if(o is CustomDataItem i)
...
}
}
The major takeaway though is that the SelectedItems must be a List<object> , they cannot be the <CustomDataItem>. I spent a couple hours searching and trying different things until I gave up and just linked the event handler in the code behind. But then I couldn't pre-select the items as described here until I changed them to the object list. So that list will populate both ways and you just have to cast it to the data type you're using.
Anyway, might've been obvious for some but maybe this will help anyone like me who just assumed the SelectedItems would be the same as the SelectedItem but in a list.
#Jason I'm laughing so much, I just figured it out and then came to post and saw your answer. Thankyou so much for your help.
For the record I found this post https://www.mfractor.com/blogs/news/migrating-listview-to-collectionview-in-xamarin-forms-interactivity
and eventually I figured out that I needed the SelectedItem as you pointed out. I think that because this wasn't needed (or is implicit) in the SelectionChanged click event.
Anyhow in my xaml
<CollectionView Grid.Row="2"
x:Name="FriendsList"
SelectionMode="Single"
SelectedItem="{Binding SelectedItem}"
SelectionChangedCommand="{Binding SelectionChangedCommand}"
SelectionChangedCommandParameter="{Binding .}" >
In my code
public Friend SelectedItem { get; set; }
//respond to item select
public ICommand SelectionChangedCommand => new Command<Object>((Object e) =>
{
Console.WriteLine($"selection made {SelectedItem.FName}");
});
Your code is much simpler of course.
You pointed out that SelectionChangedCommandParameter="{Binding .}" was (probably) not needed, so what is it's purpose?
What is the object e that is being returned in my code? I assume it is related to the SelectionChangedCommandParameter?
In my immediate window I get
e
{Census.MainPage}
base: {Microsoft.Maui.Controls.ContentPage}
AddFriendCommand: {Microsoft.Maui.Controls.Command}
SelectedItem: {Census.Classes.Friend}
SelectionChangedCommand: {Microsoft.Maui.Controls.Command<object>}
And is it possible to trace through from the xaml to the code. For instance when I was trying to figure things out I would have liked to have trapped the item click event in the xaml and see what is was doing? (Especially since it didn't at times touch a breakpoint in my code.
Just idle questions and not expecting or needing an answer unless someone is so inclined.
Thank you much again #Jason, you are a star! :)
I have this situation where I have a constraint layout. Within it lies two views. An ImageView and a TextView. When either of these Views is clicked, I want both to produce a feedback (text color change for textview and drawable tint in imageview) but I can't seem to think of a way to do these unless I put them inside another viewgroup.
Can someone show me how this could be done in constraint Layout? thank you.
Take a look at performClick().
performClick
boolean performClick ()
Call this view's OnClickListener, if it is defined. Performs all normal actions associated with clicking: reporting accessibility event, playing a sound, etc.
The idea is that when one view is clicked, your code will call performClick() on the other view. You will have to make sure that you inhibit any duplication of actions if the two views do the same function.
Other than doing this in code, I don't know of a way using just XML. There is the concept of a Group in ConstraintLayout but that just a way to control the visibility of the members of the group and does not extend to other properties.
I would use another enclosing view group unless you have a requirement not to. I just seems easier.
Use Group concept in ConstraintLayout refer: https://developer.android.com/reference/android/support/constraint/Group ,https://riggaroo.co.za/constraintlayout-guidelines-barriers-chains-groups/ ,
in java
Group group = findViewById(R.id.group);
int refIds[] = group.getReferencedIds();
for (int id : refIds) {
findViewById(id).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// your code here.
}
});
}
Kotlin:
fun Group.setAllOnClickListener(listener: View.OnClickListener?) {
referencedIds.forEach { id ->
rootView.findViewById<View>(id).setOnClickListener(listener)
}
}
Then call the function on the group:
group.setAllOnClickListener(View.OnClickListener {
// your code here.
})
I'm trying to Weld my custom ContentPart SitesPart containing a ContentField of type TaxonomyField but it is not working for me. When i attach this part from UI it works perfectly fine and i see the TaxonomyField in edit mode as well as in display mode.
Following is the Activating method of my ContentHandler.
protected override void Activating(ActivatingContentContext context)
{
if (context.ContentType == "Page")
{
context.Builder.Weld<SitesPart>();
}
}
I tried to go deep into the Weld function and found out that it is not able to find correct typePartDefinition. It goes inside the condition if (typePartDefinition == null) which creates an empty typePartDefinition with no existing ContentFields etc.
// obtain the type definition for the part
var typePartDefinition = _definition.Parts.FirstOrDefault(p => p.PartDefinition.Name == partName);
if (typePartDefinition == null) {
// If the content item's type definition does not define the part; use an empty type definition.
typePartDefinition =
new ContentTypePartDefinition(
new ContentPartDefinition(partName),
new SettingsDictionary());
}
I would be highly thankful for any guidance.
Oh, you are totally right, the part is welded but if there are some content fields, they are not welded. The ContentItemBuilder try to retrieve the part definition through the content type definition on which we want to add the part. So, because it's not possible, a new content part is created but with an empty collection of ContentPartFieldDefinition...
I think that the ContentItemBuilder would need to inject in its constructor and use a ContentPartDefinition or more generally an IContentDefinitionManager... But, for a quick workaround I've tried the following that works
In ContentItemBuilder.cs, replace this
public ContentItemBuilder Weld<TPart>()...
With
public ContentItemBuilder Weld<TPart>(ContentPartDefinition contentPartDefinition = null)...
And this
new ContentPartDefinition(partName),
With
contentPartDefinition ?? new ContentPartDefinition(partName),
And in you part handler, inject an IContentDefinitionManager and use this
protected override void Activating(ActivatingContentContext context) {
if (context.ContentType == "TypeTest") {
var contentPartDefinition = _contentDefinitionManager.GetPartDefinition(typeof(FruitPart).Name);
context.Builder.Weld<FruitPart>(contentPartDefinition);
}
}
Best
To attach a content part to a content type on the fly, you can use this in your handler
Filters.Add(new ActivatingFilter<YourContentPart>("YourContentType"));
There are many examples in the source code
Best
I'm working with java me, I built an app using forms displayables. I'm trying to switch to other forms, based on the user's input in a textfield item. For example, I want the user to be able to type in the number "1" in the textfield and then be taken to form1 or type in "2" and be taken to form2 etc.
What's the code to do this?
Here's what I did but it's not working as expected:
form.setItemStateListener(new ItemStateListener() {
public void itemStateChanged(Item item) {
if (item == TextField) {
if ("1".equals(TextField.getString())) {
switchDisplayable(null, form1);
}
}
}
I've done as adviced. I added a command to the textfield item and listen on it to read textfield contents and then compare the contents as a string, to switch forms. See my code below, still not working. I think maybe there's something I'm missing or my logic is not right.
form.setCommandListener(new CommandListener() {
public void commandAction(Command command, Displayable displayable) {
if (command == getTextFieldItemCommand()) {
if ("1".equals(TextField.getString())) {
switchDisplayable(null, form1);
} else if ("2".equals(TextField.getString())){
switchDisplayable(null, form2);
}
}
}
It looks like you expect method itemStateChanged to be invoked when it feels convenient to you, like at every character entry in the text field.
Above expectation is wrong, specified behavior is explained in API javadocs:
It is up to the device to decide when it considers a new value to have been entered into an Item... In general, it is not expected that the listener will be called after every change is made...
Given above, using itemStateChanged the way you want makes very little sense, consider changing design of your MIDlet.
I for one would probably just add a command Go and command listener to the form or text field and read text field contents when user invokes that command to find out which displayable they want to switch to.
Lets say I want a different main image for each page, situated above the page title. Also, I need to place page specific images in the left bar, and page specific text in the right bar. In the right and left bars, I also want layer specific content.
I can't see how I can achieve this without creating a layer for each and every page in the site, but then I end up with a glut of layers that only serve one page which seems too complex.
What am I missing?
If there is a way of doing this using Content parts, it would be great if you can point me at tutorials, blogs, videos to help get my head round the issue.
NOTE:
Sitefinity does this sort of thing well, but I find Orchard much simpler for creating module, as well as the fact that it is MVC which I find much easier.
Orchard is free, I understand (and appreciate) that. Just hoping that as the product evolves this kind of thing will be easier?
In other words, I'm hoping for the best of all worlds...
There is a feature in the works for 1.5 to make that easier, but in the meantime, you can already get this to work quite easily with just a little bit of code. You should first add the fields that you need to your content type. Then, you are going to send them to top-level layout zones using placement. Out of the box, placement only targets local content zones, but this is what we can work around with a bit of code by Pete Hurst, a.k.a. randompete. Here's the code:
ZoneProxyBehavior.cs:
=====================
using System;
using System.Collections.Generic;
using System.Linq;
using ClaySharp;
using ClaySharp.Behaviors;
using Orchard.Environment.Extensions;
namespace Downplay.Origami.ZoneProxy.Shapes {
[OrchardFeature("Downplay.Origami.ZoneProxy")]
public class ZoneProxyBehavior : ClayBehavior {
public IDictionary<string, Func<dynamic>> Proxies { get; set; }
public ZoneProxyBehavior(IDictionary<string, Func<dynamic>> proxies) {
Proxies = proxies;
}
public override object GetMember(Func<object> proceed, object self, string name) {
if (name == "Zones") {
return ClayActivator.CreateInstance(new IClayBehavior[] {
new InterfaceProxyBehavior(),
new ZonesProxyBehavior(()=>proceed(), Proxies, self)
});
}
// Otherwise proceed to other behaviours, including the original ZoneHoldingBehavior
return proceed();
}
public class ZonesProxyBehavior : ClayBehavior {
private readonly Func<dynamic> _zonesActivator;
private readonly IDictionary<string, Func<dynamic>> _proxies;
private object _parent;
public ZonesProxyBehavior(Func<dynamic> zonesActivator, IDictionary<string, Func<dynamic>> proxies, object self) {
_zonesActivator = zonesActivator;
_proxies = proxies;
_parent = self;
}
public override object GetIndex(Func<object> proceed, object self, IEnumerable<object> keys) {
var keyList = keys.ToList();
var count = keyList.Count();
if (count == 1) {
// Here's the new bit
var key = System.Convert.ToString(keyList.Single());
// Check for the proxy symbol
if (key.Contains("#")) {
// Find the proxy!
var split = key.Split('#');
// Access the proxy shape
return _proxies[split[0]]()
// Find the right zone on it
.Zones[split[1]];
}
// Otherwise, defer to the ZonesBehavior activator, which we made available
// This will always return a ZoneOnDemandBehavior for the local shape
return _zonesActivator()[key];
}
return proceed();
}
public override object GetMember(Func<object> proceed, object self, string name) {
// This is rarely called (shape.Zones.ZoneName - normally you'd just use shape.ZoneName)
// But we can handle it easily also by deference to the ZonesBehavior activator
return _zonesActivator()[name];
}
}
}
}
And:
ZoneShapes.cs:
==============
using System;
using System.Collections.Generic;
using Orchard.DisplayManagement.Descriptors;
using Orchard;
using Orchard.Environment.Extensions;
namespace Downplay.Origami.ZoneProxy.Shapes {
[OrchardFeature("Downplay.Origami.ZoneProxy")]
public class ZoneShapes : IShapeTableProvider {
private readonly IWorkContextAccessor _workContextAccessor;
public ZoneShapes(IWorkContextAccessor workContextAccessor) {
_workContextAccessor = workContextAccessor;
}
public void Discover(ShapeTableBuilder builder) {
builder.Describe("Content")
.OnCreating(creating => creating.Behaviors.Add(
new ZoneProxyBehavior(
new Dictionary<string, Func<dynamic>> { { "Layout", () => _workContextAccessor.GetContext().Layout } })));
}
}
}
With this, you will be able to address top-level layout zones using Layout# in front of the zone name you want to address, for example Layout#BeforeContent:1.
ADDENDUM:
I have used Bertrand Le Roy's code (make that Pete Hurst's code) and created a module with it, then added 3 content parts that are all copies of the bodypart in Core/Common.
In the same module I have created a ContentType and added my three custom ContentParts to it, plus autoroute and bodypart and tags, etc, everything to make it just like the Orchard Pages ContentType, only with more Parts, each with their own shape.
I have called my ContentType a View.
So you can now create pages for your site using Views. You then use the ZoneProxy to shunt the custom ContentPart shapes (Parts_MainImage, Parts_RightContent, Parts_LeftContent) into whatever Zones I need them in. And job done.
Not quite Sitefinity, but as Bill would say, Good enough.
The reason you have to create your own ContentParts that copy BodyPart instead of just using a TextField, is that all TextFields have the same Shape, so if you use ZoneProxy to place them, they all end up in the same Zone. Ie, you build the custom ContentParts JUST so that you get the Shapes. Cos it is the shapes that you place with the ZoneProxy code.
Once I have tested this, I will upload it as a module onto the Orchard Gallery. It will be called Wingspan.Views.
I am away on holiday until 12th June 2012, so don't expect it before the end of the month.
But essentially, with Pete Hurst's code, that is how I have solved my problem.
EDIT:
I could have got the same results by just creating the three content parts (LeftContent, RightContent, MainImage, etc), or whatever content parts are needed, and then adding them to the Page content type.
That way, you only add what is needed.
However, there is some advantage in having a standard ContentType that can be just used out of the box.
Using placement (Placement.info file) you could use the MainImage content part for a footer, for example. Ie, the names should probably be part 1, part 2, etc.
None of this would be necessary if there was a way of giving the shape produced by the TextField a custom name. That way, you could add as may TextFields as you liked, and then place them using the ZoneProxy code. I'm not sure if this would be possible.