Programatically build UI for ListView's items - c++

From various questions, I know it is impossible to create DataTemplate from the code behind without using the XamlReader. So I want to ask if there is a way to programatically generates the UI for each Item in a ListView. I don't seem to find any relevant event handler or member of ListView for this purpose. Ideally, I want the ListView to invoke my handler code to generate UI for each data item it needs to display.

Imitating the official XamlTreeView sample, I have tried overriding some ListView method such as PrepareContainerForItemOverride but this won't work. The solution I found is as #JustinXL suggests: producing ListViewItem and insert them to the ListView->Items directly
//assume that items is a list of items we want to bind
myListView->Items->Clear();
for(auto i : items)
{
ListViewItem^ v = ref new ListViewItem();
v->Content = GenerateUIFor(i);
myListView->Items->Append(v); // NOTE: a wrapping ListViewItem is required!
}
To support usual data binding, it would be best to make the data structure to cache the generated UI. For example,
ref class MyDataStructure
{
public:
property ListViewItem^ Item
{
ListViewItem^ get()
{
if (_item == nullptr)
GenerateUI();
return _item;
}
}
void GenerateUI()
{
_item = ref new ListViewItem();
_text_block = ref new TextBlock(); // sample
_item->Content = _text_block;
UpdateUI();
}
// Invoke this when changing the state of this object
void UpdateUI()
{
if (_text_block != nullptr) // sample
{
_text_block->Text = this->ToString(); // sample
}
}
private:
ListViewItem^ _item;
TextBlock^ _text_block;
};
The downside of this is of course we can't make use of data virtualization. But it works properly for small set of data. For large set, one can use website's approach with Next and Prev button to load next page or go back to previous page.

ItemContainerGenerator should let you construct the entire UI for an item inside a list view. Unfortunately there doesn't appear to be much in the way of non MSDN documentation/samples for this.
Alternatively if you can maintain a list of all the DataTemplates you might need to show, you could use a DataTemplateSelector to choose which DataTemplate you want to show for each individual item.

Related

Unity3D: GridLayout keeps adding 1 element under the last element when count is 1

Unity3D 2018.2
So I have a canvas that gets deactivated and reactivated at users choice. I have a List filled with transforms in which I populated the Grid with. I also have another List to hold all the images that will be used to populate the Grid with, since what the grid is being populated with are buttons containing the transform. For example if I click the button and run Debug.Log("transform.name"), I should see all my different transforms.
Problem 1: Every time this canvas gets enabled or disabled, the grid
keeps adding 1 element under the initial one, and after being
enabled/disabled again, another element is instantiated under that
one.
+
Problem 2: Also none of these instantiated buttons get called. Maybe
the problem here is due to the 1st problem?
Here is the code I have for inside the button I have
public class SatelliteButton : MonoBehaviour {
[SerializeField]
private Image myIcon;
public void SetIcon(Sprite mySprite)
{
myIcon.sprite = mySprite;
}
public void OnMouseEnter()
{
Debug.Log(transform.name);
}
}
Here is the code for populating the grid
public class SatelliteGridControl : MonoBehaviour {
private List<Transform> satelliteListFromPlanet;
[SerializeField]
private GameObject buttonTemplate;
[SerializeField]
private GridLayoutGroup gridGroup;
[SerializeField]
private List<Sprite> iconSprites;
// Use this for initialization
void OnEnable()
{
getSatellitesInPlanet();
genInventory();
}
// Get Satellites
private void getSatellitesInPlanet()
{
satelliteListFromPlanet = new List<Transform>();
// Get current planet
Transform currentPlanet = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<HandleCamera>().targetToLookAt;
// Check inside for satellites
foreach (Transform satellite in currentPlanet)
{
// Check transform for tag
if (satellite.CompareTag("Satellite"))
{
// Add each transform from planet to array
satelliteListFromPlanet.Add(satellite);
}
}
}
// Handle Grid
private void genInventory()
{
if (satelliteListFromPlanet.Count < 6)
{
gridGroup.constraintCount = satelliteListFromPlanet.Count;
}
else
{
gridGroup.constraintCount = 5;
}
foreach (Transform sat in satelliteListFromPlanet)
{
GameObject newButton = Instantiate(buttonTemplate) as GameObject;
newButton.SetActive(true);
newButton.GetComponent<SatelliteButton>().SetIcon(iconSprites[Random.Range(0, iconSprites.Count)]);
newButton.transform.SetParent(buttonTemplate.transform.parent, false);
}
}
}
I appreciate the help! Learning about grid layouts with List<>!
In genInventory() you Instantiate a new button for every Transform in satelliteListFromPlanet. Since only 1 is added it seems that your list only contains 1 element.
But you never destroy/remove this Instantiated GameObjects, so the next time you re-enable the object, OnEnable will be called again and new prefabs are Instantiated.
Solution:
Make sure to store the Instantiated objects somewhere e.g.
private List<GameObject> instances = new List<GameObject>();
//....
foreach (Transform sat in satelliteListFromPlanet)
{
GameObject newButton = Instantiate(buttonTemplate) as GameObject;
newButton.SetActive(true);
newButton.GetComponent<SatelliteButton>().SetIcon(iconSprites[Random.Range(0, iconSprites.Count)]);
newButton.transform.SetParent(buttonTemplate.transform.parent, false);
instances.Add(newButton);
}
And than you can destroy them when you disable the object:
private void OnDisable()
{
foreach(var instance in instances)
{
Destroy(instance);
}
}
Problem 1: Every time this canvas gets enabled or disabled, the grid keeps adding 1 element under the initial one, and after being enabled/disabled again, another element is instantiated under that one.
Right now you're calling getSatellitesInPlanet() on SatelliteGridControl's OnEnabled() method. This method is called every time the object is set to active. If you just want to call your method once, use Start.
Problem 2: Also none of these instantiated buttons get called. Maybe
the problem here is due to the 1st problem?
I don't think the problems are related. Can you confirm that your buttonTemplate prefab has an Image element and its RaycastTarget is enabled?
Just one tip, I would set the type of buttonTemplate to SatelliteButton, not GameObject. That way you can instantiate it as type SatelliteButton and avoid the need to call:
newButton.GetComponent<SatelliteButton>()

Qt - Hash table contains incorrect values

I'm doing my controller. When I click on an item in my ListWidget, the following method is called :
void ContactBookController::setCurrentlySelectedItem(QListWidgetItem *item)
{
setCurrentItem(*item);
m_window.setEditButtonsState(true);
}
And the setCurrentItem() method is as follows : (m_current_item is a private variable):
void ContactBookController::setCurrentItem(const QListWidgetItem &current_item)
{
m_current_item = current_item;
}
Now, when I create a contact, I add an item to the QListWidget, but I also create a Contact object, but I also bind them together in a QHash so I know what QListWidgetItem corresponds to what Contact. In short, here is what I did :
void ContactBookController::createContact()
{
auto new_contact = m_contact_book.createContact();
if(new_contact != nullptr)
{
new_contact->setName(tr("New contact"));
}
auto list_item = m_window.createContact(new_contact->getName());
m_window.clearSelection();
m_contact_map.insert(list_item, new_contact);
}
Now, when clicking on a QListWidgetItem, I activate the edit button and I would like to retrieve the corresponding Contact object. However, when doing this, the Contact object doesn't seem to be correct. Indeed, if I use a method on him (like getName()), my application instantly crashes.
Here is what I did :
void ContactBookController::editContact()
{
auto list_item = m_current_item;
auto contact = m_contact_map.value(&list_item); /* doesn't work */
}
My hash table is declared as such :
QHash<QListWidgetItem*, Contact*> m_contact_map;
Any idea what I did wrong ?
Your hash has the type QHash<QListWidgetItem*, Contact>. So, mapping a item pointer to a contact value.
When you save the mapping for a specific item with m_contact_map.insert(list_item, new_contact), you add a mapping from the item pointer to the contact. But when you try to retrieve the contact with m_contact_map.value(&list_item), you look up the value for the pointer to the local list_item variable, which points to somewhere on the stack, and has nothing to do with the pointer to the item that is shown in the view.
Either you need to save to pointer to the selected value, i.e. make m_current_item a QListWidgetItem *m_current_item, or you simply use QListWidget::currentItem() to retrieve the current item without the need for an additional member variable.
(Side note: You should check for currentItem() != nullptr, since a list widget does not necessarily has an item selected.)

Enumerating (looping through) an IQueryable<Type> instance

partial void Query1_PreprocessQuery(string Filter1, ref IQueryable<Type> query)
{
//how can I loop through the query and add data to a custom list
}
Generally speaking, the _PreprocessQuery method is for defining the contents of the query and not doing anything with those contents (which would be Post processing). So a simple method might read:
partial void Query1_PreprocessQuery(string Filter1, ref IQueryable<Type> query)
{
query = query.Where(x => x.FilterColumn == Filter1);
}
This is happening on the server side so even if you did intercept the results, I think it would be tricky to get any list you created back to the client side.
Once the query results have been passed to the client screen, you can then loop through the query and use the contents however you like, for example using Screen Property methods like Query1_Loaded or Collection methods like Query1_Changed depending on what you're trying to achieve. Untested code, but something like this:
partial void Query1_Loaded(bool succeeded)
{
// Loop through the rows on the screen ...
foreach (IEntityObject rowData in this.Query1)
{
// Reference individual values like this ...
string FilterResult = rowData.Details.Properties["FilterColumn"].Value.ToString()
}
}
}

QML: How to use a dynamically created component with a customized internal object?

I'm looking for a way to dynamically create a component and object, and use the component. It seems like most of the examples available, such as those in the Qt documentation or other StackOverflow posts, are related to using the object returned from createObject(), whereas I want to use the component which contains the (customized) object.
I've stripped out a lot of extraneous detail (e.g. the CustomContainer gets pushed onto/popped off of StackViews), but the following code hopefully illustrates what I'm trying to do... Basically, I would like to have the CustomControl rectangle with foo = 10 and bar = 10, but it seems to load with the defaults instead. There will be multiple "custom control" types and multiple "custom container" objects so I need to be able to support this generically.
The Qt documentation talks about creation contexts, which I assume is my problem, but I'm not sure how to fix this. I'd prefer a purely QML solution, but C++ is fine if that's where the solution lies.
Main.qml:
CustomContainer {
id: myCustomContainer
}
CustomContainer {
id: myOtherCustomContainer
}
function addCustomControl( control, args ) {
var newComponent = Qt.createComponent( control )
var newObj = newComponent.createObject( myCustomContainer, args )
return newComponent
}
myCustomContainer.loaderSource = addCustomControl( "CustomControl.qml", { "foo": 10, "bar": 10 } )
myOtherCustomContainer.loaderSource = addCustomControl( "CustomControl.qml", { "foo": 20, "bar": 20 } )
CustomControl.qml:
Rectangle {
property int foo: 5
property int bar: 5
}
CustomContainer.qml:
Item {
property Component loaderSource
onLoaderSourceChanged: {
myLoader.sourceComponent = loaderSource
}
Loader {
id: myLoader
onSourceComponentChanged: {
doStuff()
}
}
}
The component does not "contain the object". The component is a prototype for objects to be instantiated. Think of it like a "type" or a class or struct in C++ vs an instance of that type.
Your code creates the component, and then creates an object from it with modified values for the properties, but the component still has its default properties, so using it as a source component will produce objects with default properties.
Furthermore, a Loader will do automatic dynamic instantiation for you. So you don't need to combine both manual and automatic, either do it manually, or leave the loader to do it.
Last, but not least, when components are instantiated by a StackView they will automatically fill it and their size will be bound to it, so it will automatically change as the StackView size changes. So just use an Item and put your content in there and layout it. Only the root item's size will be bound to the StackView size, its children items will have their own sizes.

Change ListBox's selected Item in Windows phone 7

I need to select an item from a list box that contains objects of my class. Here is my code:
the load event:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
XDocument loadedData = XDocument.Load("file.xml");
var data = from query in loadedData.Descendants("element")
select new myClass
{
First = (string)query.Element("first"),
Second = (string) query.Element("second")
};
List<myClass> d = data.ToList<myClass>();
myList = d;
myListBox.ItemsSource = data;
}
and then my button which is supposed to change the selected Item:
private void button1_Click(object sender, RoutedEventArgs e)
{
myListBox.SelectedItem = myList[100];
}
am I doing something wrong here?
myList isn't the collection you've bound to the list.
Either make d a wider scoped variable and refer to that in button1_click
or
store data in myList rather than a copy of it.
For efficiency, I would set the ItemsSource to 'd' rather than 'data'. The enumeration returned by the linq query is lazy, so it gets evaluated every time the UI updates. The array you have is eagerly created, so later lookups are fast.
Looks like a little bug here. I was able to inconstantly replicate a similar problem.
I used the standard VS template for a Databound Application. The template comes with some sample data and a populated list box. I added a button which set the selected item to the 15th item in the collection. This worked as expected. However, when I scrolled the list up to the top it wouldn't return to the 15th record when I clicked the button. Taking a guess here, what you're running into is another symptom of the same problem.
To solve this I first set the SelectedIndex to -1 which essentially deselects the item.
private void button1_Click(object sender, RoutedEventArgs e)
{
myListBox.SelectedIndex = -1;
myListBox.SelectedItem = myList[100];
}
I'm curious if this also solves your problem.