Flex 4.5: Setting textAlign GridColumn's itemRenderer through AS3 - datagrid

Maybe this is really simple, but I can't figure out how to set 'textAlign' property for default itemRenderer in AS3 (not mxml). I need to adjust it based on type's properties, 'int' or 'Number' aligned right, 'String' aligned left and so on.
I'm using spark DataGrid and listening FlexEvent.CREATION_COMPLETE event; I can't cast itemRenderer to DefaultGridItemRenderer, and ClassFactory doesn't provide setStyle method.
public function adjustGrid (e:Event):void
{
for (var i:int=0; i<grd.columns.length; i++)
{
var gridColumn:GridColumn = GridColumn(grd.columns.getItemAt(i));
DefaultGridItemRenderer(gridColumn.itemRenderer).setStyle("textAlign", "right");
//ClassFactory(gridColumn.itemRenderer).setStyle("textAlign", "right");
}
}
Any help I will appreciate.
Thanks.

extends DefaultGridItemRenderer.......
override public function getTextStyles():TextFormat{
var tf:TextFormat = super.getTextStyles();
tf.align = "right";
return tf;
}

extends DefaultGridItemRenderer and add method:
public function set styles(obj:Object):void
{
for (var styleProp:String in obj)
{
setStyle(styleProp,obj[styleProp]);
}
}
Then You may put any styles like that:
var itemRenderer:ClassFactory = new ClassFactory(DefaultGridItemRenderer);
itemRenderer.properties = {
styles:{textAlign:"right", fontWeight:"bold"},
someOtherProp:"Hello"};
rightList.itemRenderer = itemRenderer;

Related

databinding formatted text to a richtextbox in silverlight 4

I need to databind formatted text to a RichTextBox. For formatting it seems that I will have to create a series of Runs with their specific formats and then add them to a paragraph and add it to the blocks property on the RichTextBox. I tried to bind a paragraph property to Blocks but it doesn't seem to allow that. Paragraph doesn't have an itemsource to bind it to a list of Runs. How can I possibly databind the list of Runs to a RichTextBox Widget ?
Thanks
Here is the solution I came up with. I created a custom RichTextViewer class and inherited from RichTextBox.
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
namespace System.Windows.Controls
{
public class RichTextViewer : RichTextBox
{
public const string RichTextPropertyName = "RichText";
public static readonly DependencyProperty RichTextProperty =
DependencyProperty.Register(RichTextPropertyName,
typeof (string),
typeof (RichTextBox),
new PropertyMetadata(
new PropertyChangedCallback
(RichTextPropertyChanged)));
public RichTextViewer()
{
IsReadOnly = true;
Background = new SolidColorBrush {Opacity = 0};
BorderThickness = new Thickness(0);
}
public string RichText
{
get { return (string) GetValue(RichTextProperty); }
set { SetValue(RichTextProperty, value); }
}
private static void RichTextPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
((RichTextBox) dependencyObject).Blocks.Add(
XamlReader.Load((string) dependencyPropertyChangedEventArgs.NewValue) as Paragraph);
}
}
}

flex select value from Combo

My goal is to create a generic function that selects a value in a combobox accoring to a value.
(My comoBox holds arrayCollection as dataProvider.)
The difficulty is infact to get a propertyname in runtime mode
public function selectComboByLabel(combo:ComboBox , propetryName:String, value:String):void {
var dp:ArrayCollection = combo.dataProvider as ArrayCollection;
for (var i:int=0;i<dp.length;i++) {
if (dp.getItemAt(i).propertyName==value) {
combo.selectedIndex = i;
return;
}
}
}
the line if (dp.getItemAt(i).propertyName==value)
is of course incorrect.
It should be arther something like: dp.getItemAt(i).getPropertyByName(propertyName)
Any clue on how to that ?
Don't use Object Property notation. Do this:
dp.getItemAt(i)[propertyName]
In addition to what Flextras said, you could also redo your for loop to make it easier to read:
for each(var item:Object in dp) {
if(item[propertyName] == value) {
combo.selectedItem = item;
return;
}
}

How do I create a Hierarchical Cursor from the dataProvider of an AdvancedDataGrid?

In a previous application that I had written, I had a Class that extended AdvancedDataGrid (ADG). It contained the following code:
package
{
public class CustomADG extends AdvancedDataGrid
{
....
// This function serves as the result handler for a webservice call that retrieves XML data.
private function webServiceResultHandler(event:ResultEvent):void
{
var resultXML:XML = new XML(event.result);
dataProvider = new HierarchicalData(resultXML.children);
}
....
public function setOpenNodes(maxDepth:int = 0):void
{
var dataCursor:IHierarchicalCollectionViewCursor = dataProvider.createCursor();
while (dataCursor.current != null)
{
if (dataCursor.currentDepth < maxDepth)
dataProvider.openNode(dataCursor.current);
dataCursor.moveNext();
}
dataProvider.refresh();
}
}
}
In this implementation, the function setOpenNodes() worked fine - it did exactly what I intended it to do - pass it a number, and open all nodes in the dataProvider at or below that level.
Now, I am creating a new ADG Class and want to reproduce this functionality:
package view
{
import mx.collections.IHierarchicalCollectionViewCursor;
public class ReportADG extends AdvancedDataGrid
{
public function ReportADG()
{
super();
}
public function setOpenNodes(maxDepth:int = 0):void
{
var dataCursor:IHierarchicalCollectionViewCursor =
dataProvider.createCursor();
while (dataCursor.current != null)
{
if (dataCursor.currentDepth < maxDepth)
dataProvider.openNode(dataCursor.current);
dataCursor.moveNext();
}
dataProvider.refresh();
}
}
}
The dataProvider is set in the parent component:
<view:ReportADG id="reportADG" dataProvider="{reportData}" />
reportData is set in another file:
reportData = new HierarchicalData(resultXML.children);
However, I am getting runtime errors:
TypeError: Error #1034: Type Coercion failed: cannot convert ListCollectionViewCursor#6f14031 to mx.collections.IHierarchicalCollectionViewCursor.
I've tried casting dataProvider as ICollectionView. I've tried then casting the ICollectionView as IHierarchicalCollectionView. I've tried all sorts of casting, but nothing seems to work. Why won't this work in this new implementation as it did in the past implementation? What do I need to do?
*** Update:
I started debugging this. I added an override setter to my ADG Class to see when dataProvider was being set:
override public function set dataProvider(value:Object):void
{
super.dataProvider = value;
}
I added a breakpoint to this setter and to my setOpenNodes() function. Sure enough, the dataProvider is being set BEFORE setOpenNodes() is called, and it is HierarchicalData. But, when the setOpenNodes() the debugger says that the dataProvider is a null ArrayCollection. It seems like this is the root issue.
I needed to call commitProperties before attempting to access the dataProvider property.
public function setOpenNodes(maxDepth:int = 0):void
{
super.commitProperties();
var dataCursor:IHierarchicalCollectionViewCursor =
dataProvider.createCursor();
while (dataCursor.current != null)
{
if (dataCursor.currentDepth < maxDepth)
dataProvider.openNode(dataCursor.current);
dataCursor.moveNext();
}
dataProvider.refresh();
}

How does one define a default style for a custom Flex component?

I'm creating a new Flex component (Flex 3). I'd like it to have a default style. Is there a naming convention or something for my .cs file to make it the default style? Am I missing something?
Christian's right about applying the CSS, but if you're planning on using the component in a library across projects, you're gonna want to write a default css file for that library. Here's how you do it:
Create a css file called "defaults.css" (Only this file name will work!) and put it at the top level under the "src" folder of your library. If the css file references any assets, they have to be under "src" as well.
(IMPORTANT!) Go to library project's Properties > Flex Library Build Path > Assets and include the css file and all assets.
That's how the Adobe team sets up all their default styles, now you can do it too. Just figured this out- huge
Two ways, generally. One's just by referencing the class name directly -- so for example, if you'd created a new component class MyComponent in ActionScript, or indirectly by making an MXML component extending another UIComponent called MyComponent, in both cases, the component would pick up the styles declared in your external stylesheet, provided that stylesheet's been imported into your application (e.g., via Style source):
MyComponent
{
backgroundColor: #FFFFFF;
}
Another way is by setting the UIComponent's styleName property (as a string):
public class MyComponent
{
// ...
this.styleName = "myStyle";
// ...
}
... and defining the style in the CSS file like so (note the dot notation):
.myStyle
{
backgroundColor: #FFFFFF;
}
Make sense?
In addition to what Christian Nunciato suggested, another option is to define a static initializer for your Flex component's styles. This allows you to set the default styles without requiring the developer to include a CSS file.
private static function initializeStyles():void
{
var styles:CSSStyleDeclaration = StyleManager.getStyleDeclaration("ExampleComponent");
if(!styles)
{
styles = new CSSStyleDeclaration();
}
styles.defaultFactory = function():void
{
this.exampleNumericStyle = 4;
this.exampleStringStyle = "word to your mother";
this.exampleClassStyle = DefaultItemRenderer //make sure to import it!
}
StyleManager.setStyleDeclaration("ExampleComponent", styles, false);
}
//call the static function immediately after the declaration
initializeStyles();
A refinement of what joshtynjala suggested:
public class CustomComponent extends UIComponent {
private static var classConstructed:Boolean = classConstruct();
private static function classConstruct():Boolean {
if (!StyleManager.getStyleDeclaration("CustomComponent")) {
var cssStyle:CSSStyleDeclaration = new CSSStyleDeclaration();
cssStyle.defaultFactory = function():void {
this.fontFamily = "Tahoma";
this.backgroundColor = 0xFF0000;
this.backgroundAlpha = 0.2;
}
StyleManager.setStyleDeclaration("CustomComponent", cssStyle, true);
}
return true;
}
}
I've read this in the docs somewhere; the classContruct method gets called automatically.
You may want to override default styles using the <fx:Style> tag or similar. If that's the case, a CSSStyleDeclaration may already exist by the time classConstructed is checked. Here's a solution:
private static var classConstructed:Boolean = getClassConstructed ();
private static function getClassConstructed ():Boolean {
var defaultCSSStyles:Object = {
backgroundColorGood: 0x87E224,
backgroundColorBad: 0xFF4B4B,
backgroundColorInactive: 0xCCCCCC,
borderColorGood: 0x333333,
borderColorBad: 0x333333,
borderColorInactive: 0x666666,
borderWeightGood: 2,
borderWeightBad: 2,
borderWeightInactive: 2
};
var cssStyleDeclaration:CSSStyleDeclaration = FlexGlobals.topLevelApplication.styleManager.getStyleDeclaration ("StatusIndicator");
if (!cssStyleDeclaration) {
cssStyleDeclaration = new CSSStyleDeclaration ("StatusIndicator", FlexGlobals.topLevelApplication.styleManager, true);
}
for (var i:String in defaultCSSStyles) {
if (cssStyleDeclaration.getStyle (i) == undefined) {
cssStyleDeclaration.setStyle (i, defaultCSSStyles [i]);
}
}
return (true);
}
To create a default style you can also have a property in your class and override the styleChanged() function in UIComponent, eg to only draw a background color across half the width of the component:
// this metadata helps flex builder to give you auto complete when writing
// css for your CustomComponent
[Style(name="customBackgroundColor", type="uint", format="color", inherit="no")]
public class CustomComponent extends UIComponent {
private static const DEFAULT_CUSTOM_COLOR:uint = 0x00FF00;
private var customBackgroundColor:uint = DEFAULT_CUSTOM_COLOR;
override public function styleChanged(styleProp:String):void
{
super.styleChanged(styleProp);
var allStyles:Boolean = (!styleProp || styleProp == "styleName");
if(allStyles || styleProp == "customBackgroundColor")
{
if(getStyle("customBackgroundColor") is uint);
{
customBackgroundColor = getStyle("customBackgroundColor");
}
else
{
customBackgroundColor = DEFAULT_CUSTOM_COLOR;
}
invalidateDisplayList();
}
// carry on setting any other properties you might like
// check out UIComponent.styleChanged() for more examples
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
graphics.clear();
graphics.beginFill(customBackgroundColor);
graphics.drawRect(0,0,unscaledWidth/2,unscaledHeight);
}
}
You could also create a setter for the customBackgroundColor that called invalidateDisplayList(), so you could also set the customBackgroundColor property programatically as well as through css.

Flex: Database driven DataGrid: arrows disappearing

In Flex I'm using the following code to allow sorting in a DataGrid (the data is paged and sorted serverside).
private function headerReleaseHandler(event:DataGridEvent):void
{
var column:DataGridColumn = DataGridColumn(event.currentTarget.columns[event.columnIndex]);
if(this.count>0)
{
if(this.query.SortField == column.dataField)
{
this.query.SortAscending = !this.query.SortAscending;
}
else
{
this.query.SortField = column.dataField;
this.query.SortAscending = true;
}
this.fill();
}
event.preventDefault();
}
This works perfectly, except that the arrows that indicate sorting isn't shown. How can I accomplish that?
Thanks!
/Niels
There is an example here if this is what you are looking for:
http://blog.flexexamples.com/2008/02/28/displaying-the-sort-arrow-in-a-flex-datagrid-control-without-having-to-click-a-column/
It looks like you need to refresh the collection used by your dataprovider.
I have encountered the same problem and the only solution I found was to override the DataGrid and create a custom one.
Here is the class:
public class DataGridCustomSort extends DataGrid
{
public function DataGridCustomSort()
{
super();
addEventListener(DataGridEvent.HEADER_RELEASE,
headerReleaseHandlerCustomSort,
false, EventPriority.DEFAULT_HANDLER);
}
public function headerReleaseHandlerCustomSort(event:DataGridEvent):void {
mx_internal::sortIndex = event.columnIndex;
if (mx_internal::sortDirection == null || mx_internal::sortDirection == "DESC")
mx_internal::sortDirection = "ASC";
else
mx_internal::sortDirection = "DESC";
placeSortArrow();
}
}
You have to specifically call the placeSortArrow() method when you get the HEADER_RELEASE event and set the column index and direction information.
in the above code what does "this" refer to is it the datagrid because I am confused by this.query.SortField , I am assuming 'this' and "query' are your own custom objects. and why are you checking for count. what count is that.
Regards
-Mohan

Resources