Bind a property from code headache - data-binding

I have tried to bind the contents of a textbox to a property I created inside the control, but without success. I have found a way to do it otherwise, but it is convoluted, and I'd prefer something simpler. Anyway, this is the final code:
public partial class DateListEditor : UserControl, INotifyPropertyChanged {
private int _newMonth;
public int newMonth {
get { return _newMonth; }
set {
if(value < 1 || value > 12)
throw new Exception("Invalid month");
_newMonth = value;
NotifyPropertyChanged("newMonth");
}
}
public DateListEditor() {
InitializeComponent();
DataContext = this;
newMonth = DateTime.Now.Month;
}
// ...
Then in the XAML:
<TextBox x:Name="uiMonth" Text="{Binding newMonth, Mode=TwoWay, ValidatesOnExceptions=True}"/>
This thing works. It will pre-fill the textbox with the current month, and validate it when focus is lost: great.
But how can I avoid the XAML line, and do everything from code? I can't seem to be able to work this out. I have tried this code, but nothing happens:
InitializeComponent();
Binding b = new Binding("Text") {
Source = newMonth,
ValidatesOnExceptions = true,
Mode = BindingMode.TwoWay,
};
uiMonth.SetBinding(TextBox.TextProperty, b);
DataContext = this;
How can I do it without setting the binding in the XAML?

Try changing this line and see if it helps
//oldway
Binding b = new Binding("Text")
//newway
Binding b = new Binding("newMonth")
the path you are giving to the Binding should be the Path to the property you want. where you are setting the source you might even be able to leave that blank

+1 tam, and don't forget about the source:
Binding b = new Binding("newMonth"){
Source = this, // the class instance that owns the property 'newMonth'
ValidatesOnExceptions = true,
Mode = BindingMode.TwoWay,
};

Related

Xamarin.Forms activate/deactivate toolbar items not working

I have a Xamarin.Form MainPage:ContentPage with a ToolbarItems Bar on top. The toolbar items are bound to my ViewModel like so:
<ToolbarItem Text="Sync" Command="{Binding ReloadCommand}" >
</ToolbarItem>
The availability of the Item depends on some logic:
private bool canReloadExecute(object arg)
{
bool result = (!IsReloading && (App.GetPersistentSetting("DeviceID") != "") && (App.GetPersistentSetting("BuildingID") != ""));
return result;
}
There is a separate dialog controlling the DeviceID and BuildingID on a different settings page. Once any of those ids is entered it is persistently stored away
App.SetPersistentSetting("DeviceID",value);
Problem is, that the menu items don't change their appearance once my code uses popAsync() to return to the Main page. I need to restart my app to see the changes. According to the debugger, canReloadExecute isn't called. Why this?
What I tried to work around this issue is to force a refresh in the MainPage's OnAppearing method like this:
public void RefreshToolbarItems()
{
TestApp.ViewModels.MainViewModel mvm = (TestApp.ViewModels.MainViewModel)BindingContext;
mvm.RefreshToolbarItems();
}
... and in the ViewModel:
public void RefreshToolbarItems()
{
OnPropertyChanged("BuildingScanCommand");
OnPropertyChanged("ReloadCommand");
}
but this code runs through but changes nothing, while the Debugger shows that the routine is indeed firing the events, they seem to go nowhere.
Any ideas how I can get my menu going?
Edit 1: "Show command initalization"
I am not shre what specifically you mean, but here is the whole code dealing with the command:
private ICommand _reloadCommand;
public ICommand ReloadCommand => _reloadCommand ?? (_reloadCommand = new Command(ExecuteReloadCommand, canReloadExecute));
private bool _isReloading = false;
public bool IsReloading
{
get => _isReloading;
set
{
_isReloading = value;
((Command)_reloadCommand).ChangeCanExecute();
OnPropertyChanged(nameof(ReloadCommand));
}
}
private bool canReloadExecute(object arg)
{
bool result = (!IsReloading && (App.GetPersistentSetting("DeviceID") != "") && (App.GetPersistentSetting("BuildingID") != ""));
return result;
}
private async void ExecuteReloadCommand(object obj)
{
IsReloading = true;
// Some code ...
IsReloading = false;
}
The goal is to disable the command, if either the command handler is already running, or if the configuration of DeviceID and/or BuildingId hasn't been done yet.
The enable/disable does almost work, if I set the DeviceId and BuildingId, and restart the app, the command is properly enabled or disabled. It doesn't work, however, if I set the Ids in a sub-page and return to the main page.
meanwhile I came to the conclusion, that firing onPropertyChange obviously doesn't make the command check its canReloadExecute. So the question is, how do I trigger this?
I finally solved the issue myself, this code works nicely for me:
public void RefreshToolbarItems()
{
((Command)BuildingScanCommand).ChangeCanExecute();
((Command)ReloadCommand).ChangeCanExecute();
}

how to update Visual Studio UI when using DynamicItemStart inside a vsix package

I'm implementing a DynamicItemStart button inside a Menu Controller. I'm loading the dynamic items for this button when Visual Studio starts. Everything is loaded correctly so the initialize method is called an I see all the new items in this Dynamic button. After the package is completely loaded I want to add more items to this Dynamic button, but since the package is already loaded the initialize method is not called again and I cannot see the new items in this Dynamic button. I only see the ones that were loaded when VS started.
Is there any way that I can force the update of this Dynamic button so it shows the new items?. I want to be able to update the VS UI after I added more items but outside the Initialize method.
The implementation I did is very similar to the one showed on this msdn example:
http://msdn.microsoft.com/en-us/library/bb166492.aspx
Does anyone know if an Update of the UI can be done by demand?
Any hints are greatly appreciated.
I finally got this working. The main thing is the implementation of a derived class of OleMenuCommand that implements a new constructor with a Predicate. This predicate is used to check if a new command is a match within the DynamicItemStart button.
public class DynamicItemMenuCommand : OleMenuCommand
{
private Predicate<int> matches;
public DynamicItemMenuCommand(CommandID rootId, Predicate<int> matches, EventHandler invokeHandler, EventHandler beforeQueryStatusHandler)
: base(invokeHandler, null, beforeQueryStatusHandler, rootId)
{
if (matches == null)
{
throw new ArgumentNullException("Matches predicate cannot be null.");
}
this.matches = matches;
}
public override bool DynamicItemMatch(int cmdId)
{
if (this.matches(cmdId))
{
this.MatchedCommandId = cmdId;
return true;
}
this.MatchedCommandId = 0;
return false;
}
}
The above class should be used when adding the commands on execution time. Here's the code that creates the commands
public class ListMenu
{
private int _baselistID = (int)PkgCmdIDList.cmdidMRUList;
private List<IVsDataExplorerConnection> _connectionsList;
public ListMenu(ref OleMenuCommandService mcs)
{
InitMRUMenu(ref mcs);
}
internal void InitMRUMenu(ref OleMenuCommandService mcs)
{
if (mcs != null)
{
//_baselistID has the guid value of the DynamicStartItem
CommandID dynamicItemRootId = new CommandID(GuidList.guidIDEToolbarCmdSet, _baselistID);
DynamicItemMenuCommand dynamicMenuCommand = new DynamicItemMenuCommand(dynamicItemRootId, isValidDynamicItem, OnInvokedDynamicItem, OnBeforeQueryStatusDynamicItem);
mcs.AddCommand(dynamicMenuCommand);
}
}
private bool IsValidDynamicItem(int commandId)
{
return ((commandId - _baselistID) < connectionsCount); // here is the place to put the criteria to add a new command to the dynamic button
}
private void OnInvokedDynamicItem(object sender, EventArgs args)
{
DynamicItemMenuCommand invokedCommand = (DynamicItemMenuCommand)sender;
if (null != invokedCommand)
{
.....
}
}
private void OnBeforeQueryStatusDynamicItem(object sender, EventArgs args)
{
DynamicItemMenuCommand matchedCommand = (DynamicItemMenuCommand)sender;
bool isRootItem = (matchedCommand.MatchedCommandId == 0);
matchedCommand.Enabled = true;
matchedCommand.Visible = true;
int indexForDisplay = (isRootItem ? 0 : (matchedCommand.MatchedCommandId - _baselistID));
matchedCommand.Text = "Text for the command";
matchedCommand.MatchedCommandId = 0;
}
}
I had to review a lot of documentation since it was not very clear how the commands can be added on execution time. So I hope this save some time whoever has to implement anything similar.
The missing piece for me was figuring out how to control the addition of new items.
It took me some time to figure out that the matches predicate (the IsValidDynamicItem method in the sample) controls how many items get added - as long as it returns true, the OnBeforeQueryStatusDynamicItem gets invoked and can set the details (Enabled/Visible/Checked/Text etc.) of the match to be added to the menu.

ASP.NET Custom Web control

I'm experiencing some problems and right now I don't know how to solve it. The web control simply updates a clock represented by a label every second. My issue is that the web control exposes a property called 'Formato' where the user can select to display in format 12 or 24 hours. This is done with an enum type where in spanish Doce means 12 and Veinticuatro means 24. This is the code for the server control:
namespace Ejercicio2RelojControl
{
public enum _FormatoHora
{
Doce,
Veinticuatro
}
[DefaultProperty("FormatoHora")]
[ToolboxData("<{0}:Ejercicio2RelojControl runat=server></{0}:Ejercicio2RelojControl>")]
[ToolboxBitmap(typeof(Ejercicio2RelojControl), "Ejercicio2RelojControl.Ejercicio2RelojControl.ico")]
//[Designer("Ejercicio2RelojControl.Ejercicio2RelojControlDesigner, Ejercicio2RelojControl")]
public class Ejercicio2RelojControl : WebControl
{
public Ejercicio2RelojControl()
{
}
[
//Bindable(true),
Category("Appearance"),
//DefaultValue(_FormatoHora.Doce),
Description(""),
]
public virtual _FormatoHora FormatoHora
{
get
{
//object t = ViewState["FormatoHora"];
//return (t == null) ? _FormatoHora.Doce : (_FormatoHora)t;
object obj2 = this.ViewState["_FormatoHora"];
if (obj2 != null)
{
return (_FormatoHora)obj2;
}
return _FormatoHora.Doce;
}
set
{
ViewState["_FormatoHora"] = value;
}
}
//Create one TimerControl
Timer timer = new Timer();
private Label clockLabel = new Label();
// Declare one Updatepanel
UpdatePanel updatePanel = new UpdatePanel();
// Now override the Load event of Current Web Control
protected override void OnLoad(EventArgs e)
{
//Text = "hh:mm:ss";
// Create Ids for Control
timer.ID = ID + "_tiker";
clockLabel.ID = ID + "_l";
// get the contentTemplate Control Instance
Control controlContainer = updatePanel.ContentTemplateContainer;
// add Label and timer control in Update Panel
controlContainer.Controls.Add(clockLabel);
controlContainer.Controls.Add(timer);
// Add control Trigger in update panel on Tick Event
updatePanel.Triggers.Add(new AsyncPostBackTrigger() { ControlID = timer.ID, EventName = "Tick" });
updatePanel.ChildrenAsTriggers = true;
// Set default clock time in label
clockLabel.Text = DateTime.Now.ToString("h:mm:ss tt");
//clockLabel.Text = DateTime.Now.ToString("H:mm:ss");
// Set Interval
timer.Interval = 1000;
// Add handler to timer
timer.Tick += new EventHandler<EventArgs>(timer_Tick);
updatePanel.RenderMode = UpdatePanelRenderMode.Block;
//Add update panel to the base control collection.
base.Controls.Add(updatePanel);
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(FormatoHora);
}
void timer_Tick(object sender, EventArgs e)
{
// Set current date time in label to move current at each Tick Event
clockLabel.Text = DateTime.Now.ToString("h:mm:ss tt");
//clockLabel.Text = DateTime.Now.ToString("H:mm:ss");
}
}
}
Now it's time to test the custom control in an asp.net web application.
<cc1:Ejercicio2RelojControl ID="Ejercicio2RelojControl1" runat="server" />
Works great! BUT when I add the property "Formato" fails at compile time:
<cc1:Ejercicio2RelojControl ID="Ejercicio2RelojControl1" runat="server" Formato="Doce" />
Compiler Error Message: CS0117: 'Ejercicio2RelojControl.Ejercicio2RelojControl' does not contain a definition for 'FormatoHora'
Why is the property Formato making the web app crash at compile time?
Thanks a lot.
EDIT:
namespace Ejercicio2RelojControl
{
public enum FormatoHora
{
Doce,
Veinticuatro
}
[DefaultProperty("FormatoHora")]
[ToolboxData("<{0}:Ejercicio2RelojControl runat=server></{0}:Ejercicio2RelojControl>")]
public class Ejercicio2RelojControl : WebControl, INamingContainer
{
public FormatoHora FormatoHora
{
get
{
object obj2 = this.ViewState["FormatoHora"];
if (obj2 != null)
{
return (FormatoHora)obj2;
}
return FormatoHora.Doce;
}
set
{
ViewState["FormatoHora"] = value;
}
}
As you can see I've changed the public property. Now the error has changed. Is the following:
Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property 'Ejercicio2RelojControl.Ejercicio2RelojControl.FormatoHora.get'
Any help appreciated. Thanks
EDIT 2:
I've discovered that the problem is on the set {}. If I comment it, all is working fine but then I cannot change FormatoHora between 12 and 24 because of is read only due to only get{} is implemented. Any help with the implementation of set{} ?
I am here for giving you the solution:
You are using the same name for the namespace and for the webcontrol (Ejercicio2RelojControl) . Simply change that and your code will work fine.
Hope it helps, despite the fact some years have passed :)

Shuffle DevExpress GridControl DataSource

I need to shuffle the GridControl's DataSource. I use this property in a UserControl:
private List<Song> _songsDataSource;
public List<Song> SongsDataSource
{
get { return _songsDataSource; }
set
{
_songsDataSource = value;
if (!value.IsNull())
{
SongsBindingList = new BindingList<Song>(value);
songsBinding.DataSource = SongsBindingList;
}
}
}
Then i use a method that i clone, shuffle and append to the SongsDataSource property:
List<Song> newList = HelpClasses.Shuffle((List<Song>) SongsDataSource.Clone());
SongsDataSource = newList;
public static List<Song> Shuffle(List<Song> source)
{
for (int i = source.Count - 1; i > 0; i--)
{
int n = rng.Next(i + 1);
Song tmp = source[n];
source[n] = source[i - 1];
source[i - 1] = tmp;
}
return source;
}
Strange thing is that it doesn't seem to reflect the changes to the GridControl even i use the GridControl.RefreshDataSource() method after set the SongsDataSource method. If i check the DataSource order, shuffle was happened successfully.
Thank you.
Since you've changed the object originally set as a DataSource, calling RefreshDataSource() won't do any good cause you can't refresh something that's no longer there. Your problem is here:
List<Song> newList = HelpClasses.Shuffle((List<Song>) SongsDataSource.Clone());
SongsDataSource = newList; // the reference has changed, the grid doesn't know what to do when RefreshDataSource() is called.
You can pass the list as it is, without the need of cloning it. Also surround the Shuffle() method call with gridControl.BeginUpdate() end gridControl.EndUpdate() to prevent any updates to the grid while the elements of the DataSource are changing.
I had such problems with DevExpress GridControl. I think, that this situation caused by GridView(http://documentation.devexpress.com/#WindowsForms/clsDevExpressXtraGridViewsGridGridViewtopic), which creates automaticly for each GridControl.
This is part of GridControl responsible for visualization of DataSource.
If you need to change DataSource try:
GridView.Columns.Clear();
GridControl.DataSource = You_New_DataSource;
GridView.RefreshData();
GridControl.RefreshDataSource();

Extending Flex DataGridColumn for custom sorting function

I extended the DataGridColumn because I wanted to include a custom itemToLabel function (to be able to show nested data in the DataGrid. See this question.
Anyways, it also needs a custom sorting function. So I have written the sorting function like so:
private function mySortCompareFunction(obj1:Object, obj2:Object):int{
var currentData1:Object = obj1;
var currentData2:Object = obj2;
//some logic here to get the currentData if the object is nested.
if(currentData1 is int && currentData2 is int){
var int1:int = int(currentData1);
var int2:int = int(currentData2);
var result:int = (int1>int2)?-1:1;
return result;
}
//so on for string and date
}
And in the constructor of my CustomDataGridColumn, I've put:
super(columnName);
sortCompareFunction = mySortCompareFunction;
Whenever I try to sort the column, I get the error "Error: Find criteria must contain at least one sort field value."
When I debug and step through each step, I see that the first few times, the function is being called correctly, but towards the end, this error occurs.
Can someone please shed some light on what is happening here?
Thanks.
I have seen this error too, and I tracked it down to one of the cells containing 'null'.
And if I remember correctly, this error also shows up, when one of the columns has a wrong 'dataField' attribute.
hth,
Koen Weyn
Just to specify how exactly I solved this problem (for the benefit of others):
Instead of using the dataField property (to which I was assigning something like data.name, data.title since I was getting data from a nested object), I created my own field nestedDataField and made it bindable. So my code basically looks like this now:
public class DataGridColumnNested extends DataGridColumn{
[Bindable] public var nestedDataField:String;
private function mySortCompareFunction(obj1:Object, obj2:Object):int{
var currentData1:Object = obj1;
var currentData2:Object = obj2;
//some logic here to get the currentData if the object is nested.
if(currentData1 is int && currentData2 is int){
var int1:int = int(currentData1);
var int2:int = int(currentData2);
var result:int = (int1>int2)?-1:1;
return result;
}
//so on for string and date
}
}
Then I assign to this new variable my dataField entry
<custom:DataGridColumnNested headerText="Name" nestedDataField="data.name"/>
And lo and behold! it works without a hitch.
I often find it easier to use the standard datafield and just write a getter function in my valueobject to use as a datafield.
For example:
//file SomeObject.as with a nested object as property
public class SomeObject
{
public var someProperty:AnotherObject;
public function get someString():String;
{
if(someProperty)
return someProperty.someString;
else
return "";
}
}
//your nested class, AnotherObject.as
public class AnotherObject
{
public var someString:String;
}
//this way sorting and the label will work without custom label/compare functions
<mx:DataGridColumn headerText="" dataField="someString"/>
The easiest way to solve the problem is change the dataField="obj.atributte" by a labelFunction. If you want you can add a sortCompareFunction too.
<mx:DataGridColumn headerText="email"
dataField="user.email" textAlign="center" />
change by
<mx:DataGridColumn headerText="email"
labelFunction="emailLabelFunction"
sortCompareFunction="emailsCompareFunction2"
textAlign="center" />
public static function emailLabelFunction(item:Object, column:DataGridColumn):String{
if (item!=null){
var user:User = (item as TpAnnouncementUser).user as User;
return user.email;
}else{
return "";
}
}
public static function emailCompareFunction(obj1:Object, obj2:Object):int{
var dato1:String = User(obj1).email.toLowerCase();
var dato2:String = User(obj2).email.toLowerCase();
return ObjectUtil.compare(dato1, dato2);
}
public static function emailsCompareFunction2(obj1:Object, obj2:Object):int{
var dato3:User = (TpAnnouncementUser(obj1).user as User);
var dato4:User = (TpAnnouncementUser(obj2).user as User);
return emailCompareFunction(dato3, dato4);

Resources