Monotouch: Need to add navigation item(BarButtonItem) and event in every page - iphone

Hi i am very new to iphone programming..i have used DialogViewController in my application.
In the following code , addButton.Clicked event will generate an new root element with sections(Table cell) and we can navigating to another page using these sections.
i need NavigationItem(RightBarButtonItem) and its event in every navigating pages to save the datas in current page
its very urgent!
Thanks.
Part of My Code:
public partial class AppDelegate : UIApplicationDelegate
{
UIWindow _window;
UINavigationController _nav;
DialogViewController _RootVC;
RootElement _rootElement;
UIBarButtonItem _addButton;
UIBarButtonItem _EditButton;
DataBaseAccess da =new DataBaseAccess();
public string _name;
EntryElement StrainName;
//Load all the datas
private bool LoadMain()
{
_window = new UIWindow (UIScreen.MainScreen.Bounds);
_rootElement = new RootElement("Strain")
{
new Section()
{
(StrainName = new EntryElement ("Strain Name","Enter Name",""))
},
new Section()
{
}
};
List ();
_RootVC = new DialogViewController (UITableViewStyle.Grouped,_rootElement,true);
_nav = new UINavigationController(_RootVC);
//_EditButton= new UIBarButtonItem(UIBarButtonSystemItem.Edit);
_EditButton = new UIBarButtonItem("Delete", UIBarButtonItemStyle.Plain,null);
_addButton = new UIBarButtonItem(UIBarButtonSystemItem.Add);
_RootVC.NavigationItem.LeftBarButtonItem = _EditButton;
_RootVC.NavigationItem.RightBarButtonItem = _addButton;
_addButton.Clicked += (sender, e) =>
{
if (StrainName.Value=="")
{
return ;
}
da.Addnew (StrainName.Value);
var strain = new Strains{Name = StrainName.Value};
var strainElement = new RootElement(StrainName.Value)
{
new Section()
{
new StringElement("Name",strain.Name)
},
new Section()
{
new EntryElement("Strain Type"," Enter Type","")
},
new Section()
{
new RootElement("Dispensory")
{
new Section()
{
new EntryElement("Dispensory"," Enter Dispensory name","")
},
new Section()
{
new EntryElement("Address"," Enter Address","")
},
new Section()
{
new EntryElement("City","Enter City","")
},
new Section()
{
new EntryElement("State","Enter State","")
},
new Section()
{
new EntryElement("Zip","Enter Zip","")
},
new Section()
{
new EntryElement("Phone","Enter Phone","")
}
}
},
new Section()
{
new EntryElement("Price","Enter Price per Gram","")
},
new Section()
{
new EntryElement("Rating","Enter Rating 1-10","")
}
};
StrainName.Value = "";
_rootElement[0].Add(strainElement);
};
_EditButton.Clicked += (sender, e) =>
{
Edit_Elements();
};
_window.RootViewController = _nav;
_window.MakeKeyAndVisible ();
return true;
}
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
return LoadMain ();
}
//List the data from DB
private void List (){
DataBaseAccess Lobj_da=new DataBaseAccess();
Lobj_da.getstrains ();
List<string> strains=Lobj_da.Starins;
foreach (string name in strains)
{
var strain = new Strains{Name = name};
var strainElement = new RootElement(name)
{
new Section()
{
new EntryElement("Name",strain.Name,strain.Name)
},
new Section()
{
new EntryElement("Strain Type"," Enter Type","")
},
new Section()
{
new RootElement("Dispensory")
{
new Section()
{
new EntryElement("Dispensory"," Enter Dispensory name","")
},
new Section()
{
new EntryElement("Address"," Enter Address","")
},
new Section()
{
new EntryElement("City","Enter City","")
},
new Section()
{
new EntryElement("State","Enter State","")
},
new Section()
{
new EntryElement("Zip","Enter Zip","")
},
new Section()
{
new EntryElement("Phone","Enter Phone","")
}
}
},
new Section()
{
new EntryElement("Price","Enter Price per Gram","")
},
new Section()
{
new EntryElement("Rating","Enter Rating 1-10","")
}
};
StrainName.Value = "";
_rootElement[0].Add(strainElement);
}
}
//
//Edit Changes
void ConfigEdit (DialogViewController dvc)
{
//dvc.NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Edit, delegate {
dvc.NavigationItem.LeftBarButtonItem = new UIBarButtonItem("Update", UIBarButtonItemStyle.Plain,null);
dvc.TableView.SetEditing (true, true);
ConfigDone (dvc);
// });
}
void ConfigDone (DialogViewController dvc)
{
dvc.NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Done, delegate {
dvc.TableView.SetEditing (false, true);
ConfigEdit (dvc);
LoadMain();
});
}
public void Edit_Elements ()
{
RootElement _rootElement_Edit;
_rootElement_Edit = new RootElement("Strain")
{
new Section()
{
}
};
DataBaseAccess LEobj_da=new DataBaseAccess();
LEobj_da.getstrains ();
List<string> strains=LEobj_da.Starins;
foreach (string name in strains){
var strain = new Strains{Name = name};
var strainElement = new RootElement(name)
{
new Section()
{
new StringElement("Name",strain.Name)
}
};
_rootElement_Edit[0].Add(strainElement);
}
var dvc = new EditingDialog (_rootElement_Edit, true);
ConfigEdit (dvc);
_nav.PushViewController (dvc, true);
}
} `

I think the best way is the create a new DialogViewController and to implement your saving code there.

You should subclass UINavigationView and all your views should inherit form it

Related

How do I populate Items in collection view from model view if I am using file picker?

I am trying to select some files from file picker . Once I select them I want to show them in my collection view. If I am trying to achieve this thing from code behind then it is working fine but if I am trying it from MVVM then it is not populating the files I have selected.
and the reason I am trying to do it with MVVM is that I want to navigate to the next page with all selected files.
Thanks.
Here is my code:
MainPage.xaml
<CollectionView Grid.ColumnSpan="2" Grid.Row="1"
SelectionMode="Single" x:Name="myCollection"
VerticalOptions="FillAndExpand"
VerticalScrollBarVisibility="Always"
ItemTemplate="{StaticResource appDataTemplate}"
ItemsSource="{Binding Items}">
</CollectionView>
Here I have binded my context.
MainPage.Xaml.cs
public MainPage(FileViewModel vm)
{
InitializeComponent();
BindingContext = vm;
}
And this is my viewModel:`[ObservableProperty]
List sourceData;
public List<Item> Items
{
get { return sourceData; }
set
{
sourceData = value;
}
}
public FileViewModel(IFolderPicker folderPicker)
{
sourceData = Items ;
_folderPicker = folderPicker;
}`
public async void Add_File(object sender, EventArgs e)
{
var CustomFileType = new FilePickerFileType(new Dictionary<DevicePlatform,
IEnumerable<String>>
{
//logic
});
var results = await FilePicker.PickMultipleAsync(new PickOptions
{
FileTypes = CustomFileType,
});
sourceData = null;
foreach (var result in results)
{
FileInfo fileInfo = new FileInfo(result.FullPath);
double size = fileSize(fileInfo);
bool fileExist = false;
if (Items != null)
{
foreach (Item item in Items)
{
if (item.FilePath.Equals(result.FullPath))
{
fileExist = true;
break;
}
}
}
else
{
Items= new ObservableCollection<Item>();
}
if (!fileExist)
{
Items.Add(new Item
{
FilePath = result.FullPath,
FileSize = size
});
}
else
{
Items= sourceData;
// await DisplayAlert("Alert", "File already exist!", "Ok");
}
}
Items = sourceData;
}
Same code is working file if I put the view models code in code behind like below:
private async void Add_File(object sender, EventArgs e)
{
var CustomFileType = new FilePickerFileType(new Dictionary<DevicePlatform,
IEnumerable<String>>
{
{ DevicePlatform.WinUI, new[]{"ics"} },
});
var results = await FilePicker.PickMultipleAsync(new PickOptions
{
FileTypes = CustomFileType,
});
myCollection.ItemsSource = null;
foreach (var result in results)
{
FileInfo fileInfo = new FileInfo(result.FullPath);
double size = fileSize(fileInfo);
bool fileExist = false;
foreach (Item item in Items)
{
if (item.FilePath.Equals(result.FullPath))
{
fileExist = true;
break;
}
}
if (!fileExist)
{
Items.Add(new Item
{
FilePath = result.FullPath,
FileSize = size
});
}
else
{
myCollection.ItemsSource = Items;
await DisplayAlert("Alert", "File already exist!", "Ok");
}
}
myCollection.ItemsSource = Items;
}
But it is not working with file view model.
I am not able to populate the collection view from view model.

Salesforce lightning input's element.set not working anymore after summer 18 release

I am using below snippet to check for valid phone number format and then trying to set the formatted value to the current input element. But after summer 18 release I'm unable to set input with new formatted value.
TestApp
<aura:application extends="force:slds">
<lightning:input type="text" label="Num" aura:id="ele" onchange="
{!c.changeNum}" />
</aura:application>
Controller:
({
changeNum : function(component, event, helper) {
helper.changeNum(component, event);
}
})
Helper:
({
changeNum : function(component, event) {
var element = event.getSource();
var phonenumber = element.get("v.value");
if(phonenumber){
var updatedValue = phonenumber.replace(/-/g, "");
if(/^\d{10}$/.test(updatedValue)){
phonenumber = updatedValue.match(new RegExp('\\d{4}$|\\d{3}', 'g')).join("-");
}
else{
var x = phonenumber.replace(/[^0-9._-]/g, "").replace(/ +/, " ");
phonenumber = x;
if(!/^[0-9-]+$/.test(phonenumber.slice(-1))){
phonenumber = phonenumber.slice(0, -1);
}
}
}
console.log(phonenumber);
element.set('v.value', phonenumber);
}
})
element.set is not able to update the formatted value. The lightning input element is still able to accept alphabets.
We can solve the issue by using Promise
({
handleInputChange : function(component, event) {
try {
var element = event.getSource();
var inputValue = element.get("v.value");
var formattedValue;
var chkPattern = new Promise(
function (resolve, reject) {
if (inputValue) {
formattedValue = inputValue.replace(/[^0-9-]/g, "").replace(/ +/, " ");
resolve(formattedValue); // fulfilled
} else {
var reason = new Error('kitten is not happy');
reject(reason); // reject
}
}
);
chkPattern.then(function (fulfilled) {
element.set('v.value', fulfilled);
}).catch(function (error) {
console.log(error.message);
});
} catch(e) {
this.consoleLog(e.stack, true)
}
}
})

How to update list view from another class in Xamarin forms?

I have created a list view in one class and called delete method from another class. Listview getting call but not updating list view if i call from another class. But its getting update when i call inside the same class. How to solve this issue?
namespace New
{
public partial class WishesPage : ContentPage
{
ListView listView = new ListView();
public WishesPage()
{
InitializeComponent();
var arr = JToken.Parse(ids);
foreach (var ite in arr.Children())
{
var itemProperties = ite.Children<JProperty>();
string contactElement = itemProperties.FirstOrDefault(x => x.Name == "contact").Value.ToString();
sample.Add(contactElement);
}
listView.ItemTemplate = new DataTemplate(typeof(CustomListCell));
listView.ItemsSource = sample;
Content = new StackLayout
{
Children =
{
listView,
}
};
}
public async Task delete(string wishid)
{
indicator.IsRunning = true;
var client = new HttpClient();
client.BaseAddress = new Uri("http:……”);
if (response == "success")
{
listView.ItemsSource = null;
listView.ItemsSource = sample;
}
}
}
public class CustomListCell : ViewCell
{
public CustomListCell()
{
wishIdLabel.SetBinding(Label.TextProperty, new Binding("contact"));
horizontalLayout.Children.Add(wishIdLabel);
var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true };
deleteAction.Clicked += async (sender, e) =>
{
WishesPage wishes = new WishesPage();
wishes.delete(wishId);
};
ContextActions.Add(deleteAction);
}
}
}
I have updated this repo that explain how to use Commands inside a ViewCell.
In your case, you should move the construction of ViewCell inside the ContentPage. Something like
lv.ItemTemplate = new DataTemplate(() =>
{
StackLayout slView = new StackLayout();
Label lDesc = new Label();
lDesc.SetBinding(Label.TextProperty, "Description", stringFormat: "DESCRIPTION: {0}");
var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true }; // red background
deleteAction.SetBinding(MenuItem.CommandProperty, new Binding("BindingContext.TrashCommand", source: this));
deleteAction.SetBinding(MenuItem.CommandParameterProperty, ".");
slView.Children.Add(lDesc);
ViewCell vc = new ViewCell() {View = slView };
vc.ContextActions.Add(deleteAction);
return vc;
}
Now, when you longpress the row, a ContextAction "Delete" appears and a TrashCommand in your ViewModel is executed (you should use MVVM...), a "these" parameter is passed (the selected obj) so you can delete it from the List
this.TrashCommand = new Command(async (object obj) => {
try
{
if (_isTapped)
return;
if (obj != null)
System.Diagnostics.Debug.WriteLine("Obj is not null");
else
System.Diagnostics.Debug.WriteLine("Obj IS null");
_isTapped = true;
var ret = await Application.Current.MainPage.DisplayAlert("Attention", "Delete this row?", "Yes", "No");
if (ret)
{
// List is your "sample" list... Removing the obj, is it reflected to ListView if you use ObservableCollection instead of List
List.Remove((Model)obj);
Count = List.Count;
}
_isTapped = false;
}
catch (Exception ex) {
_isTapped = false;
await Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
}
});
}

Show pop-up when user clicked on the line

Need to show a pop-up when user clicks on the line. Code as below but does not work:
var ClickLon;
var ClickLat;
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
defaultHandlerOptions: {
'single': true,
'double': false,
'pixelTolerance': 0,
'stopSingle': false,
'stopDouble': false
},
initialize: function(options) {
this.handlerOptions = OpenLayers.Util.extend(
{}, this.defaultHandlerOptions
);
OpenLayers.Control.prototype.initialize.apply(
this, arguments
);
this.handler = new OpenLayers.Handler.Click(
this, {
'click': this.trigger
}, this.handlerOptions
);
},
trigger: function(e) {
var lonlat = map.getLonLatFromPixel(e.xy);
ClickLon = lonlat.lon;
ClickLat = lonlat.lat;
}
});
function onPopupClose(evt) {
selectControl.unselect(selectedFeature);
}
function onFeatureSelect(feature) {
selectedFeature = feature;
id = feature.id;
alert(ClickLon);
var lonLat = new OpenLayers.LonLat(ClickLon, ClickLat).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
popup = new OpenLayers.Popup.FramedCloud("chicken",
lonLat,
null,
"<div style='font-size:.8em'>" +CableLineText_arr[id] +"</div>",
null, true, onPopupClose);
feature.popup = popup;
map.addPopup(popup);
}
function onFeatureUnselect(feature) {
map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}
...
var lineLayer = new OpenLayers.Layer.Vector("Line Layer");
map.addLayer(lineLayer);
map.addControl(new OpenLayers.Control.DrawFeature(lineLayer, OpenLayers.Handler.Path));
var click = new OpenLayers.Control.Click();
map.addControl(click);
click.activate();
selectControl = new OpenLayers.Control.SelectFeature(lineLayer,
{onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
drawControls = {
polygon: new OpenLayers.Control.DrawFeature(lineLayer,
OpenLayers.Handler.Polygon),
select: selectControl
};
for(var key in drawControls) {
map.addControl(drawControls[key]);
}
Map projection is EPSG:4326.
Line drawing as:
var points = new Array(
new OpenLayers.Geometry.Point(47, 32.24),
new OpenLayers.Geometry.Point(45, 33),
new OpenLayers.Geometry.Point(49, 35)
);
var line = new OpenLayers.Geometry.LineString(points);
line.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
var style = {
strokeColor: '#0000ff',
strokeOpacity: 0.5,
strokeWidth: 5
};
var lineFeature = new OpenLayers.Feature.Vector(line, null, style);
alert(lineFeature.id);
lineLayer.addFeatures([lineFeature]);
Trying to combine these two examples: http://openlayers.org/dev/examples/select-feature-openpopup.html and http://openlayers.org/dev/examples/click.html
I do not see the place where you activate your control.SelectFeature.

Binding dropdown when ajax form in submitted in mvc2 asp.net

My requirement is simple, there are two dropdowns in my view. First dropdown is filled be default and second dropdown has to be filled based on values from first dropdown.
My view is
<script type='text/javascript'>
$(function() {
$('#ddlRoles').change(function() {
$(this).parents('form').submit();
});
});
< % using (Ajax.BeginForm("UpdateDropdownForm", new AjaxOptions { UpdateTargetId = "txtDropdownValue" }))
{ %>
<%= Html.DropDownList("ddlRoles", (IEnumerable<SelectListItem>)ViewData["RolesData"])%>
<%= Html.DropDownList("ddlUsers", (IEnumerable<SelectListItem>)ViewData["UsersList"])%>
<% } %>
My controller is
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["RolesData"] = GetDropdownList();
List<SelectListItem> usersList = new List<SelectListItem>();
usersList.Add(new SelectListItem() { Text = "Select" });
ViewData["UsersList"] = usersList;
TempData["UsersList"] = usersList;
return View();
}
public IEnumerable<SelectListItem> UpdateDropdownForm(string ddlRoles)
{
ViewData["UsersList"] = GetUsersList();
TempData["UsersList"] = GetUsersList();
return GetUsersList();
}
public List<SelectListItem> GetDropdownList()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem() { Text = "Admin", Value = "1" });
list.Add(new SelectListItem() { Text = "Employee", Value = "2" });
list.Add(new SelectListItem() { Text = "Manager", Value = "3" });
return list;
}
public List<SelectListItem> GetUsersList()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem() { Text = "Administrator", Value = "10" });
list.Add(new SelectListItem() { Text = "Ramesh", Value = "20" });
list.Add(new SelectListItem() { Text = "Satish", Value = "30" });
return list;
}
}
Here, im able to post the first dropdown data, and im setting the second dropdown data in viewdata/tempdata and in view im binding the data to second dropdown. But this is not working.
For now, when first dropdown is changed, im just binding second dropdown. but what if i want to fill a dropdown and display data in two text boxes. What do i have to do in that case?
How do i solve this.
please help.
You may find the following answer useful for generating cascading dropdown lists.