How to find framework element inside viewmodel using Prism - mvvm

I previously used Caliburn.Micro for my projects before universal windows application. Now I'm porting my apps to universal windows and decided to use Prism Library. Because there are lots of uwp sample for that. But I'm too beginner and don't know how to convert my old viewmodels.
I'm using webview to show some generated html. In caliburn I can find webview in viewmodel using OnViewLoaded event;
protected override void OnViewLoaded(object view)
{
base.OnViewLoaded(view);
var frameworkElement = view as FrameworkElement;
if (frameworkElement == null)
throw new ArgumentException();
var browser = frameworkElement.FindName("browser") as WebView;
if (browser == null)
throw new ArgumentException();
_webBrowser = browser;
}
But I didn't find any event can provide this. In prism there are only OnNavigatedTo and OnNavigatingFrom events.
Do prism have workaround for that?

Sorry about late reply,
I aggree with Igor and Tseng that will break MVVM pattern. But I'm trying to do something complex. Maybe there is a way of doing with it MVVM but I don't want to lose too much time on this.
What I found solution for the problem is as following. I wrote a VisualHelper
public class VisualHelper
{
public static T FindVisualChildInsideFrame<T>(DependencyObject depObj) where T : DependencyObject
{
var frame = FindVisualChild<Frame>(depObj);
if (frame != null && frame.Content is Page)
return FindVisualChild<T>(frame.Content as Page);
return null;
}
public static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
return (T)child;
}
T childItem = FindVisualChild<T>(child);
if (childItem != null)
return childItem;
}
}
return null;
}
}
In my viewmodel, using following code finds WebView control. I'm using SplitView control thats why I'm using FindVisualChildInsideFrame method.
public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
{
base.OnNavigatedTo(e, viewModelState);
var browser = VisualHelper.FindVisualChildInsideFrame<WebView>(Window.Current.Content);
}

Related

Use PopupExtensions.ShowPopupAsync function in Custom Control in MAUI

I created a custom control in MAUI that must work if user select with a click or tap, a Popup must show with some content, let's say for example a Calculator instead a Keyboard. I'm using CommunityToolkit.Maui. But the sentence
var popup = new PickerControl();
var result = await PopupExtensions.ShowPopupAsync<PickerControl>(this, popup);
throw me an error because this in inside the control and expects a Page, so need to know how handle the page or parent page in the same control. Picker control is the Popup with the content.
The code:
public partial class EntryCalculator : Frame
{
TapGestureRecognizer _tapGestureRecognizer;
public EntryCalculator()
{
InitializeComponent();
}
///Properties here
private void Initialize()
{
_tapGestureRecognizer = new TapGestureRecognizer();
}
private async static void IsDisplayPickerPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var controls = (EntryCalculator)bindable;
if (newValue != null)
{
if ((bool)newValue)
{
var popup = new PickerControl();
var response = PopupExtensions.ShowPopupAsync<PickerControl>(this, popup);
if (response != null && response is decimal)
{
controls.Value = (decimal)response;
}
}
}
}
///... other methods
At first, you can get the current page from the navigation stack:
If you use the shell:
Page currentpage = Shell.Current.Navigation.NavigationStack.LastOrDefault();
If you use the NavigationPage:
Page currentpage = Navigation.NavigationStack.LastOrDefault();
Or just only use:Page currentpage = App.Current.MainPage.Navigation.NavigationStack.LastOrDefault();. The App.Current.MainPage will be the Shell or the NavigationPage, it depends on what you used in your project.
In addition, you can get the current page from the custom control. Such as:
public static class ViewExtensions
{
/// <summary>
/// Gets the page to which an element belongs
/// </summary>
/// <returns>The page.</returns>
/// <param name="element">Element.</param>
public static Page GetParentPage (this VisualElement element)
{
if (element != null) {
var parent = element.Parent;
while (parent != null) {
if (parent is Page) {
return parent as Page;
}
parent = parent.Parent;
}
}
return null;
}
}

How to customize collectionview in dotnetmaui

I am porting my Xamarin Forms application to dotnet maui and I want to customize the collection view for android so that the items will stack from the end. I have done it in Xamarin Forms as follows,
public class ChatCollectionViewRenderer : CollectionViewRenderer
{
public ChatCollectionViewRenderer(Context context) : base(context)
{
this.SetItemViewCacheSize(20);
this.HasFixedSize = true;
}
protected override LayoutManager SelectLayoutManager(IItemsLayout layoutSpecification)
{
var manager = new LinearLayoutManager(Context, LinearLayoutManager.Vertical, false);
manager.StackFromEnd = true;
return manager;
}
}
How to do it in maui using handlers?
Found it, it can be done like this,
Microsoft.Maui.Controls.Handlers.Items.CollectionViewHandler.Mapper.AppendToMapping("ChatStackFromEnd", (h, v) =>
{
var recycleView = h.PlatformView;
var manager = new AndroidX.RecyclerView.Widget.LinearLayoutManager(recycleView.Context, AndroidX.RecyclerView.Widget.LinearLayoutManager.Vertical, false);
manager.StackFromEnd = true;
recycleView.SetLayoutManager(manager);
});
Trying it out...

Managing PDF usage rights in iText7

I'm using PdfReader.HasUsageRights() and PdfReader.RemoveUsageRights() in iTextSharp v5. Can't seem to find similar functionality in iText7?
There is probably no direct alternative but it's easy to implement those methods yourself:
public boolean hasUsageRights(PdfDocument pdfDocument) {
PdfDictionary perms = pdfDocument.getCatalog().getPdfObject().getAsDictionary(PdfName.Perms);
if (perms == null) {
return false;
}
return perms.containsKey(new PdfName("UR")) || perms.containsKey(PdfName.UR3);
}
public void removeUsageRights(PdfDocument pdfDocument) {
PdfDictionary perms = pdfDocument.getCatalog().getPdfObject().getAsDictionary(PdfName.Perms);
if (perms == null) {
return;
}
perms.remove(new PdfName("UR"));
perms.remove(PdfName.UR3);
if (perms.size() == 0) {
pdfDocument.getCatalog().remove(PdfName.Perms);
}
}
If you need the first method then you can pass either a document created with PdfDocument(PdfReader, PdfWriter) constructor or with PdfDocument(PdfReader) one. If you need the second method then you need to pass a document created in stamping mode, i.e. with PdfDocument(PdfReader, PdfWriter) constructor

MvvmCross Monotouch C# - Binding Int Property - Mode: TwoWay

I am new to MvvmCross and I have a question.
I noticed that the following binding code works in one way only:
{ this, "{'CurrentIndex':{'Path':'CurrentIndex','Mode':'TwoWay'}}" }
CurrentIndex is an Int Property in the View
CurrentIndex is also an Int Property in the ViewModel
This way works!
ViewModel => View
But not this way!
View => ViewModel
I have a collection of ViewControllers and my goal was to call a DeleteCommand for the CurrentIndex in the viewModel.
However,
"Android and Touch 2 way bindings are incomplete"
Reference: MvvmCross experiences, hindsight, limitations?
My guess is the TwoWay mode only works for Controls (UILabel, UITextfield, ...) but not for Properties.
So, is there a good way to make it works in both ways? Or Are there any alternatives to my problem?
Patrick
In order for a binding to transfer any value between a View to a ViewModel, then it needs to hook into some event when the value changes.
In the ViewModel, this event is always the event in the INotifyProperty interface.
In the View/Activity, there is one single pattern employed - so each binding has to hook into a separate event. For example, the Text on EditText is hooked up using the TextChanged event (see MvxEditTextTextTargetBinding.cs) while the value in a SeekBar is hooked up using a Listener object rather than an event (see MvxSeekBarProgressTargetBinging.cs).
So if you wanted to implement this two-way binding for your activity, then you could do this by:
declaring an event - CurrentIndexChanged - in your activity (MyActivity) which is fired whenever CurrentIndex changes
declare a custom binding for your MyActivity which programmatically links CurrentIndex and CurrentIndexChanged
adding the custom binding to the binding registry during Setup
For example, your activity might include:
public event EventHandler CurrentIndexChanged;
private int _currentIndex;
public int CurrentIndex
{
get { return _currentIndex; }
set { _currentIndex = value; if (CurrentIndexChanged != null) CurrentIndexChanged(this, EventArgs.Empty); }
}
And you might then declare a binding class like:
public class MyBinding : MvxPropertyInfoTargetBinding<MyActivity>
{
public MyBinding (object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
View.CurrentIndexChanged += OnCurrentIndexChanged;
}
public override MvxBindingMode DefaultMode
{
get
{
return MvxBindingMode.TwoWay;
}
}
private void OnCurrentIndexChanged(object sender, EventArgs ignored)
{
FireValueChanged(View.CurrentIndex);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
View.CurrentIndexChanged -= OnCurrentIndexChanged;
}
}
}
And you'd need to tell the binding system about this binding in setup like:
registry.RegisterFactory(new MvxSimplePropertyInfoTargetBindingFactory(typeof(MyBinding), typeof(MyActivity), "CurrentIndex"));
However... at a practical level, if you are operating in C# rather than in XML, then you might be better off in this case using C# to simply update the ViewModel rather than using declarative binding in this case.
To be clear... in this case, I would most probably just write the Activity property as:
public int CurrentIndex
{
get { return _currentIndex; }
set { _currentIndex = value; ViewModel.CurrentIndex = value; }
}
Or... I'd consider not having this property in the Activity at all.
If it helps, there's some more information on custom bindings in:
MonoTouch MVVMCross binding to instance variables
In MvvmCross how do I do custom bind properties
Hope this helps! IMHO the bindings are there to help you when you're working in XML - you don't have to use them...
Stuart
UPDATE If you are going to do lots of these and follow the same name pattern - using property named X with changed EventHandler event named XChanged then something like this might work - it uses reflection to find the event automagically:
public class MyBinding<T> : MvxPropertyInfoTargetBinding<T>
where T : class
{
private readonly PropertyInfo _propertyInfo;
private readonly EventInfo _eventInfo;
public MyBinding(object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
_propertyInfo = targetPropertyInfo;
var eventName = _propertyInfo.Name + "Changed";
_eventInfo = View.GetType().GetEvent(eventName);
if (_eventInfo == null)
{
throw new MvxException("Event missing " + eventName);
}
if (_eventInfo.EventHandlerType != typeof(EventHandler))
{
throw new MvxException("Event type mismatch for " + eventName);
}
var addMethod = _eventInfo.GetAddMethod();
addMethod.Invoke(View, new object[] { new EventHandler(OnChanged) });
}
public override MvxBindingMode DefaultMode
{
get
{
return MvxBindingMode.TwoWay;
}
}
private void OnChanged(object sender, EventArgs ignored)
{
var value = _propertyInfo.GetValue(View, null);
FireValueChanged(value);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
var removeMethod = _eventInfo.GetRemoveMethod();
removeMethod.Invoke(View, new object[] { new EventHandler(OnChanged) });
}
}
}

How to achieve a dynamic controller and action method in ASP.NET MVC?

In Asp.net MVC the url structure goes like
http://example.com/{controller}/{action}/{id}
For each "controller", say http://example.com/blog, there is a BlogController.
But my {controller} portion of the url is not decided pre-hand, but it is dynamically determined at run time, how do I create a "dynamic controller" that maps anything to the same controller which then based on the value and determines what to do?
Same thing with {action}, if the {action} portion of my url is also dynamic, is there a way to program this scenario?
Absolutely! You'll need to override the DefaultControllerFactory to find a custom controller if one doesn't exist. Then you'll need to write an IActionInvoker to handle dynamic action names.
Your controller factory will look something like:
public class DynamicControllerFactory : DefaultControllerFactory
{
private readonly IServiceLocator _Locator;
public DynamicControllerFactory(IServiceLocator locator)
{
_Locator = locator;
}
protected override Type GetControllerType(string controllerName)
{
var controllerType = base.GetControllerType(controllerName);
// if a controller wasn't found with a matching name, return our dynamic controller
return controllerType ?? typeof (DynamicController);
}
protected override IController GetControllerInstance(Type controllerType)
{
var controller = base.GetControllerInstance(controllerType) as Controller;
var actionInvoker = _Locator.GetInstance<IActionInvoker>();
if (actionInvoker != null)
{
controller.ActionInvoker = actionInvoker;
}
return controller;
}
}
Then your action invoker would be like:
public class DynamicActionInvoker : ControllerActionInvoker
{
private readonly IServiceLocator _Locator;
public DynamicActionInvoker(IServiceLocator locator)
{
_Locator = locator;
}
protected override ActionDescriptor FindAction(ControllerContext controllerContext,
ControllerDescriptor controllerDescriptor, string actionName)
{
// try to match an existing action name first
var action = base.FindAction(controllerContext, controllerDescriptor, actionName);
if (action != null)
{
return action;
}
// #ray247 The remainder of this you'd probably write on your own...
var actionFinders = _Locator.GetAllInstances<IFindAction>();
if (actionFinders == null)
{
return null;
}
return actionFinders
.Select(f => f.FindAction(controllerContext, controllerDescriptor, actionName))
.Where(d => d != null)
.FirstOrDefault();
}
}
You can see a lot more of this code here. It's an old first draft attempt by myself and a coworker at writing a fully dynamic MVC pipeline. You're free to use it as a reference and copy what you want.
Edit
I figured I should include some background about what that code does. We were trying to dynamically build the MVC layer around a domain model. So if your domain contained a Product class, you could navigate to products\alls to see a list of all products. If you wanted to add a product, you'd navigate to product\add. You could go to product\edit\1 to edit a product. We even tried things like allowing you to edit properties on an entity. So product\editprice\1?value=42 would set the price property of product #1 to 42. (My paths might be a little off, I can't recall the exact syntax anymore.) Hope this helps!
After a little more reflection, there may be a bit simpler way for you to handle the dynamic action names than my other answer. You'll still need to override the default controller factory. I think you could define your route like:
routes.MapRoute("Dynamic", "{controller}/{command}/{id}", new { action = "ProcessCommand" });
Then on your default/dynamic controller you'd have
public ActionResult ProcessCommand(string command, int id)
{
switch(command)
{
// whatever.
}
}
You need to write your own IControllerFactory (or perhaps derive from DefaultControllerFactory) and then register it with ControllerBuilder.
Iam working with it in .Core but i'll share it's MVC version for all, after that i will share the core version
case OwnerType.DynamicPage:
var dp = mediator.Handle(new Domain.DynamicPages.DynamicPageDtoQuery { ShopId = ShopId, SeoId = seoSearchDto.Id }.AsSingle());
if (dp != null)
{
return GetDynamicPage(dp.Id);
}
break;
// some codes
private ActionResult GetDynamicPage(int id)
{
var routeObj = new
{
action = "Detail",
controller = "DynamicPage",
id = id
};
var bController = DependencyResolver.Current.GetService<DynamicPageController>();
SetControllerContext(bController, routeObj);
return bController.Detail(id);
}
// and
private void SetControllerContext(ControllerBase controller, object routeObj)
{
RouteValueDictionary routeValues = new RouteValueDictionary(routeObj);
var vpd = RouteTable.Routes["Default"].GetVirtualPath(this.ControllerContext.RequestContext, routeValues);
RouteData routeData = new RouteData();
foreach (KeyValuePair<string, object> kvp in routeValues)
{
routeData.Values.Add(kvp.Key, kvp.Value);
}
foreach (KeyValuePair<string, object> kvp in vpd.DataTokens)
{
routeData.DataTokens.Add(kvp.Key, kvp.Value);
}
routeData.Route = vpd.Route;
if (routeData.RouteHandler == null)
routeData.RouteHandler = new MvcRouteHandler();
controller.ControllerContext = new ControllerContext(this.ControllerContext.HttpContext, routeData, controller);
}