Hiding Floating action button when parent scrolled - c#

I'm creating a custom FAB button for both android and iOS platforms using Xamarin.Forms.
Everything is working fine, but now I want to be able to somehow receive scrolled events from the nearest parent of the FAB button if any, so I will be able to hide the FAB button when the user is scrolling and then show it again after 2 seconds of scrolling finished?.
The parent could be a plain ScrollView item, or it could be a ListView.
Can this be achieved via the same custom renderers for each platform? Or, can this even be achieved at all?
This is what I did so far:
FabButton class:
public partial class FabButton : Button
{
public static BindableProperty ButtonColorProperty = BindableProperty.Create(nameof(ButtonColor), typeof(Color), typeof(FabButton), Color.Accent);
public Color ButtonColor
{
get => (Color)GetValue(ButtonColorProperty);
set => SetValue(ButtonColorProperty, value);
}
public FabButton()
{
InitializeComponent();
}
}
iOS custom renderer:
public class FabButtonRenderer:ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if(e.NewElement == null)
return;
if (Element.WidthRequest <= 0)
Element.WidthRequest = 60;
if (Element.HeightRequest <= 0)
Element.HeightRequest = 60;
if (Element.Margin == new Thickness(0, 0, 0, 0))
Element.Margin = new Thickness(0, 0, 20, 20);
Element.CornerRadius = (int) Element.WidthRequest / 2;
Element.BorderWidth = 0;
Element.Text = null;
Control.BackgroundColor = ((FabButton) Element).ButtonColor.ToUIColor();
}
public override void Draw(CGRect rect)
{
base.Draw(rect);
Layer.ShadowRadius = 0.2f;
Layer.ShadowColor = UIColor.Black.CGColor;
Layer.ShadowOffset = new CGSize(1, 1);
Layer.ShadowOpacity = 0.80f;
Layer.ShadowPath = UIBezierPath.FromOval(Layer.Bounds).CGPath;
Layer.MasksToBounds = false;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(FabButton.ButtonColor))
Control.BackgroundColor = ((FabButton) Element).ButtonColor.ToUIColor();
}
}
android custom renderer:
public class FabButtonRenderer: Xamarin.Forms.Platform.Android.AppCompat.ViewRenderer<FabButton,FloatingActionButton>
{
public static void InitRenderer() { }
public FabButtonRenderer(Context context):base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<FabButton> e)
{
base.OnElementChanged(e);
if (e.NewElement == null)
return;
if (e.NewElement.HeightRequest <= 0)
e.NewElement.HeightRequest = 85;
if (e.NewElement.WidthRequest <= 0)
e.NewElement.WidthRequest = 75;
if (e.NewElement.Margin.Equals(new Thickness(0, 0, 0, 0)))
e.NewElement.Margin = new Thickness(0, 0, 5, 10);
var fabButton = new FloatingActionButton(Context);
ViewCompat.SetBackgroundTintList(fabButton, ColorStateList.ValueOf(Element.ButtonColor.ToAndroid()));
fabButton.UseCompatPadding = true;
if (!string.IsNullOrEmpty(Element.Image?.File))
fabButton.SetImageDrawable(Context.GetDrawable(Element.Image.File));
fabButton.Click += FabButton_Clicked;
SetNativeControl(fabButton);
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
Control.BringToFront();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Element.ButtonColor))
ViewCompat.SetBackgroundTintList(Control, ColorStateList.ValueOf(Element.ButtonColor.ToAndroid()));
if (e.PropertyName == nameof(Element.Image))
{
if (!string.IsNullOrEmpty(Element.Image?.File))
Control.SetImageDrawable(Context.GetDrawable(Element.Image.File));
}
base.OnElementPropertyChanged(sender, e);
}
public void FabButton_Clicked(object sender, EventArgs e)
{
Element.SendClicked();
}
}

I think Scrollview's "Scrolled" event can help you , you will get X & Y axis values , based on it you have to hide your fab button while it's scrolling.
And for it after 2 seconds you can use "Device.StartTimer" .

Unfortunately, there is no built-in way to do this.Since in my case, the Floating Action Button might be affected by ScrollView control scrolling, or a list view control scrolling, or others.The only way for me to do this that I can think of is to specify explicitly to which ScrollView control the Floating Action Button should be connected, and since this will be a troublesome to implement when the Floating Action Button should be connected to a list view ScrollView and since it's better to use the MVVM pattern, I have find a simpler way to this.
First I declared an interface IFloatingActionButtonHost:
public interface IFloatingActionButtonHost
{
bool ShouldBeHiddenWhenScrolling { get; }
event Action LinkedScrollViewScrolled;
}
And then, I declared a BindableProperty inside the FabButton control like this:
public static BindableProperty ButtonHostProperty = BindableProperty.Create(nameof(ButtonHost), typeof(IFloatingActionButtonHost), typeof(FabButton));
public IFloatingActionButtonHost ButtonHost
{
get => (IFloatingActionButtonHost)GetValue(ButtonHostProperty);
set => SetValue(ButtonHostProperty, value);
}
And in the Renderer for example, on iOS renderer, I checked for this property if it's not null, and if the Floating Action Button should be hidden when the target ScrollView get scrolled or not and then subscribed to the event in the interface.
var fabButton = (FabButton)Element;
if (fabButton.ButtonHost != null && fabButton.ButtonHost.ShouldBeHiddenWhenScrolling)
{
fabButton.ButtonHost.LinkedScrollViewScrolled += OnLinkedScrollView_Scrolled;
}
And then I handled the event in the renderer:
private void OnLinkedScrollView_Scrolled()
{
Element.IsVisible = false;
Device.StartTimer(TimeSpan.FromSeconds(3), () =>
{
if(Element != null){
Element.IsVisible = true;
}
return false;
});
}
The OnElementPropertyChanged implementation should be changed as well.
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(FabButton.ButtonColor))
Control.BackgroundColor = ((FabButton) Element).ButtonColor.ToUIColor();
else if(e.PropertyName == nameof(FabButton.ButtonHost)){
var fabButton = (FabButton)Element;
if (fabButton.ButtonHost != null && fabButton.ButtonHost.ShouldBeHiddenWhenScrolling)
{
fabButton.ButtonHost.LinkedScrollViewScrolled += OnLinkedScrollView_Scrolled;
}
}
}
On Each page code-behind, I make the page inherit form this interface, and just passed the page instance to the target ViewModel.
P.S. For ListView I had to write a custom renderer to expose the Scrolled event. Sorry, I haven't find a better way to do this.
This is my attempt to solve this problem, if you have a better solution, please just write another answer to this question and I will mark it as the best answer.

Related

How to fire TextChanged event on a Xamarin Forms entry field programmatically?

We have setup some Xamarin behavior for not null entry fields etc, this fires when the user makes a change to a field and we then changed the entry border color, red for invalid.
However, we'd also like to reuse this behaviors when a submit button is tapped.
So I need to fire the TextChanged event manually, any ideas how I can do this, now sure if it's possible ?
public class NotEmptyEntryBehaviour : Behavior<Entry>
{
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += OnEntryTextChanged;
base.OnAttachedTo(bindable);
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= OnEntryTextChanged;
base.OnDetachingFrom(bindable);
}
void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
if (args == null)
return;
var oldString = args.OldTextValue;
var newString = args.NewTextValue;
}
}
If you want an alternative you can use one of the pre-built validation behaviors that comes with Xamarin.CommunityToolkit package, like TextValidationBehavior (by specifying a Regexp) or any more specific derived ones (example NumericValidationBehavior) that may fit your needs or even create a custom one by sub-classing ValidationBehavior.
It let you define custom styles for Valid and InValid states, but more important for the question has an async method called ForceValidate().
Also the Flags property could be interesting.
NotEmptyEntryBehaviour seems closer to TextValidationBehavior with MinimumLenght=1
xaml
<Entry Placeholder="Type something..." x:Name="entry">
<Entry.Behaviors>
<xct:TextValidationBehavior Flags="ValidateOnValueChanging"
InvalidStyle="{StaticResource InvalidEntryStyle}"
ValidStyle="{StaticResource ValidEntryStyle}"/>
</Entry.Behaviors>
</Entry>
Code
await (entry.Behaviors[0] as TextValidationBehavior)?.ForceValidate();
Docs
https://learn.microsoft.com/en-us/xamarin/community-toolkit/behaviors/charactersvalidationbehavior
Repo Samples
https://github.com/xamarin/XamarinCommunityToolkit/tree/main/samples/XCT.Sample/Pages/Behaviors
EDIT
If you want to run the validation from the ViewModel you need to bind ForceValidateCommand as explained in this GitHub discussion/question.
We have setup some Xamarin behavior for not null entry fields etc, this fires when the user makes a change to a field and we then changed the entry border color, red for invalid.
You can create custom Entry with behavior to get.
The first I’m going to do is to create a new control that inherits from Entry and will add three properties: IsBorderErrorVisible, BorderErrorColor, ErrorText.
public class ExtendedEntry : Entry
{
public static readonly BindableProperty IsBorderErrorVisibleProperty =
BindableProperty.Create(nameof(IsBorderErrorVisible), typeof(bool), typeof(ExtendedEntry), false, BindingMode.TwoWay);
public bool IsBorderErrorVisible
{
get { return (bool)GetValue(IsBorderErrorVisibleProperty); }
set
{
SetValue(IsBorderErrorVisibleProperty, value);
}
}
public static readonly BindableProperty BorderErrorColorProperty =
BindableProperty.Create(nameof(BorderErrorColor), typeof(Xamarin.Forms.Color), typeof(ExtendedEntry), Xamarin.Forms.Color.Transparent, BindingMode.TwoWay);
public Xamarin.Forms.Color BorderErrorColor
{
get { return (Xamarin.Forms.Color)GetValue(BorderErrorColorProperty); }
set
{
SetValue(BorderErrorColorProperty, value);
}
}
public static readonly BindableProperty ErrorTextProperty =
BindableProperty.Create(nameof(ErrorText), typeof(string), typeof(ExtendedEntry), string.Empty);
public string ErrorText
{
get { return (string)GetValue(ErrorTextProperty); }
set
{
SetValue(ErrorTextProperty, value);
}
}
}
Then creating custom render to android platform.
[assembly: ExportRenderer(typeof(ExtendedEntry), typeof(ExtendedEntryRenderer))]
namespace FormsSample.Droid
{
public class ExtendedEntryRenderer : EntryRenderer
{
public ExtendedEntryRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control == null || e.NewElement == null) return;
UpdateBorders();
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Control == null) return;
if (e.PropertyName == ExtendedEntry.IsBorderErrorVisibleProperty.PropertyName)
UpdateBorders();
}
void UpdateBorders()
{
GradientDrawable shape = new GradientDrawable();
shape.SetShape(ShapeType.Rectangle);
shape.SetCornerRadius(0);
if (((ExtendedEntry)this.Element).IsBorderErrorVisible)
{
shape.SetStroke(3, ((ExtendedEntry)this.Element).BorderErrorColor.ToAndroid());
}
else
{
shape.SetStroke(3, Android.Graphics.Color.LightGray);
this.Control.SetBackground(shape);
}
this.Control.SetBackground(shape);
}
}
}
Finally, Creating an Entry Behavior, handle the error to provide ui feedback to the user when validation occurs
public class EmptyEntryValidatorBehavior : Behavior<ExtendedEntry>
{
ExtendedEntry control;
string _placeHolder;
Xamarin.Forms.Color _placeHolderColor;
protected override void OnAttachedTo(ExtendedEntry bindable)
{
bindable.TextChanged += HandleTextChanged;
bindable.PropertyChanged += OnPropertyChanged;
control = bindable;
_placeHolder = bindable.Placeholder;
_placeHolderColor = bindable.PlaceholderColor;
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
ExtendedEntry customentry = (ExtendedEntry)sender;
if (!string.IsNullOrEmpty(customentry.Text))
{
((ExtendedEntry)sender).IsBorderErrorVisible = false;
}
else
{
((ExtendedEntry)sender).IsBorderErrorVisible = true;
}
}
protected override void OnDetachingFrom(ExtendedEntry bindable)
{
bindable.TextChanged -= HandleTextChanged;
bindable.PropertyChanged -= OnPropertyChanged;
}
void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == ExtendedEntry.IsBorderErrorVisibleProperty.PropertyName && control != null)
{
if (control.IsBorderErrorVisible)
{
control.Placeholder = control.ErrorText;
control.PlaceholderColor = control.BorderErrorColor;
control.Text = string.Empty;
}
else
{
control.Placeholder = _placeHolder;
control.PlaceholderColor = _placeHolderColor;
}
}
}
}
Update:
You can change custom entry's IsBorderErrorVisible in button.click, to call this from submit button.
private void btn1_Clicked(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(entry1.Text))
{
entry1.IsBorderErrorVisible = true;
}
}
<customentry:ExtendedEntry
x:Name="entry1"
BorderErrorColor="Red"
ErrorText="please enter name!">
<customentry:ExtendedEntry.Behaviors>
<behaviors:EmptyEntryValidatorBehavior />
</customentry:ExtendedEntry.Behaviors>
</customentry:ExtendedEntry>

how do I make beautiful flipping images?

When I opened the game launcher, I noticed how the news was implemented there.
And I really liked this idea, so I decided to do it in my project, first of all I made a panel, stuffed a few images into it, and then actually made two buttons with which I plan to flip through the images. BUT how to do it smoothly? Here is where the problem is, I do not understand how to make a smooth flipping of
the image
I can't tell how the images are sliding, flipping, stretching or whatever, but I think WinForms with GDI+ isn't the best choice. I think WPF would be better. I would also recommend using a suitable library for those kind of image manipulations.
However, if you want it very(!) simple you could use this class:
public class SlideAnimation
{
public event EventHandler<AnimationEventArgs> AnimationFinished;
private readonly Control Control;
private readonly Timer Timer;
private float fromXPosition;
public SlideAnimation(Control ctrl)
{
Control = ctrl;
Timer = new Timer();
Timer.Interval = 10;
Timer.Tick += Timer_Tick;
Control.Paint += Control_Paint;
}
public float Speed { get; set; }
public Image From { get; set; }
public Image To { get; set; }
public AnimationDirection Direction { get; set; }
public bool IsRunning
{
get
{
return Timer.Enabled;
}
}
public void StartAnimation()
{
// maybe move those checks into the setter of the corresponding property
if (this.From == null)
throw new InvalidOperationException();
if (this.To == null)
throw new InvalidOperationException();
if (this.Speed <= 0)
throw new InvalidOperationException();
fromXPosition = 0;
Timer.Enabled = true;
}
protected void OnAnimationFinished(AnimationEventArgs e)
{
AnimationFinished?.Invoke(this, e);
}
private void Timer_Tick(object sender, EventArgs e)
{
// increase or decrease the position of the first image
fromXPosition = fromXPosition + (this.Speed * this.Direction);
Control.Invalidate();
if (Math.Abs(fromXPosition) >= this.From.Width)
{
Timer.Enabled = false;
OnAnimationFinished(new AnimationEventArgs(this.Direction));
}
}
private void Control_Paint(object sender, PaintEventArgs e)
{
if (!Timer.Enabled)
return;
// draw both images next to each other depending on the direction
e.Graphics.DrawImage(this.From, new PointF(fromXPosition, 0));
e.Graphics.DrawImage(this.To, new PointF(fromXPosition - (this.From.Width * this.Direction), 0));
}
}
public enum AnimationDirection
{
Forward = -1,
Backward = 1
}
public class AnimationEventArgs : EventArgs
{
public AnimationEventArgs(AnimationDirection direction)
{
Direction = direction;
}
public AnimationDirection Direction { get; }
}
This class will only draw the images while the animation is active. Every other invalidation will not trigger the Control_Paint method.
Use following code for your Form:
public class Form1
{
private List<Image> imgList = new List<Image>();
private int currentIndex = 0;
private SlideAnimation animation;
public Slideshow()
{
InitializeComponent();
imgList.Add(Image.FromFile("pic1.bmp"));
imgList.Add(Image.FromFile("pic2.bmp"));
imgList.Add(Image.FromFile("pic3.bmp"));
imgList.Add(Image.FromFile("pic4.bmp"));
imgList.Add(Image.FromFile("pic5.bmp"));
animation = new SlideAnimation(this.Panel1);
animation.Speed = 20;
animation.AnimationFinished += AnimationFinished;
}
private void btnPrev_Click(object sender, EventArgs e)
{
if (currentIndex == 0)
return;
if (animation.IsRunning)
return;
animation.Direction = AnimationDirection.Backward;
animation.From = imgList[currentIndex];
animation.To = imgList[currentIndex - 1];
animation.StartAnimation();
}
private void btnNext_Click(object sender, EventArgs e)
{
if (currentIndex == imgList.Count - 1)
return;
if (animation.IsRunning)
return;
animation.Direction = AnimationDirection.Forward;
animation.From = imgList[currentIndex];
animation.To = imgList[currentIndex + 1];
animation.StartAnimation();
}
private void AnimationFinished(object sender, AnimationEventArgs e)
{
currentIndex = currentIndex - (1 * e.Direction);
}
private void Panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(imgList[currentIndex], 0, 0);
}
}
Since there are a lot of drawing operations you may use a panel which supports DoubleBuffer.
public class DoubleBufferedPanel : Panel
{
public DoubleBufferedPanel()
{
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
}
}
Keep in mind that this example is very simple and far from "fancy".

Xamarin Forms picker OK or Cancel button pressed detection

I am developing applications with Xamarin Forms. I have some problems with the picker component.
After picking up with the Picker, I need to determine whether the OK or Cancel button is pressed.
I tried Focus and Unfocus, but it doesn't help me figure out which user is pressing the OK or Cancel button.
Solution:
You should rewrite the toolbar of Picker in CustomRenderer
iOS
[assembly:ExportRenderer(typeof(Picker),typeof(MyPickerRenderer))]
namespace App6.iOS
{
public class MyPickerRenderer:PickerRenderer
{
public MyPickerRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if(Control!=null)
{
UIPickerView pickerView = (UIPickerView)Control.InputView;
// get the button Done and rewrite the event
UIToolbar toolbar = (UIToolbar)Control.InputAccessoryView;
UIBarButtonItem done = new UIBarButtonItem("OK", UIBarButtonItemStyle.Done, (object sender, EventArgs click) =>
{
MessagingCenter.Send<Object>(this,"Ok_Clicked");
});
UIBarButtonItem cancel = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, (object sender, EventArgs click) =>
{
MessagingCenter.Send<Object>(this, "Cancel_Clicked");
});
UIBarButtonItem empty = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null);
toolbar.Items = new UIBarButtonItem[] { cancel,empty, done };
}
}
}
}
Android
[assembly: ExportRenderer(typeof(Picker), typeof(MyPickerRenderer))]
namespace App6.Droid
{
public class MyPickerRenderer : PickerRenderer
{
IElementController ElementController => Element as IElementController;
public MyPickerRenderer(Context context) : base(context)
{
}
private AlertDialog _dialog;
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (e.NewElement == null || e.OldElement != null)
return;
Control.Click += Control_Click;
}
protected override void Dispose(bool disposing)
{
Control.Click -= Control_Click;
base.Dispose(disposing);
}
private void Control_Click(object sender, EventArgs e)
{
Picker model = Element;
var picker = new NumberPicker(Context);
if (model.Items != null && model.Items.Any())
{
picker.MaxValue = model.Items.Count - 1;
picker.MinValue = 0;
picker.SetDisplayedValues(model.Items.ToArray());
picker.WrapSelectorWheel = false;
picker.Value = model.SelectedIndex;
}
var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical };
layout.AddView(picker);
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, true);
var builder = new AlertDialog.Builder(Context);
builder.SetView(layout);
builder.SetTitle(model.Title ?? "");
builder.SetNegativeButton("Cancel ", (s, a) =>
{
MessagingCenter.Send<Object>(this, "Cancel_Clicked");
});
builder.SetPositiveButton("Ok ", (s, a) =>
{
ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value);
// It is possible for the Content of the Page to be changed on SelectedIndexChanged.
// In this case, the Element & Control will no longer exist.
if (Element != null)
{
if (model.Items.Count > 0 && Element.SelectedIndex >= 0)
Control.Text = model.Items[Element.SelectedIndex];
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is also possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
}
MessagingCenter.Send<Object>(this, "Ok_Clicked");
});
_dialog = builder.Create();
_dialog.DismissEvent += (ssender, args) =>
{
ElementController?.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
};
_dialog.Show();
}
}
}
And you can handle the event in forms by using MessagingCenter.
in contentPage
public MainPage()
{
InitializeComponent();
MessagingCenter.Subscribe<Object>(this, "Ok_Clicked", (sender)=> {
picker.Unfocus();
DisplayAlert("Title", "Ok has been clicked", "cancel");
//do something you want
});
MessagingCenter.Subscribe<Object>(this, "Cancel_Clicked", (sender) => {
picker.Unfocus();
DisplayAlert("Title", "Cancel has been clicked", "cancel");
//do something you want
});
}

UWP drag and drop custom type/class

Hy there,
I'm trying to enable drag & drop between 2 GridViews, I managed to do it with the custom types of the "DataPackage" class (SetText, SetBitmap, etc..) but I can't figure out how to do this with a custom class/type.
Both GridViews are data-bound to the same custom class (only a couple of properties, int, string, bitmapimage), I simply would like to drag directly this data items from one GridView to the other.
Thank you very much for your help!
So to summarize for the benefit of others, I added these to event handlers to DataTemplate content, as I only wanted items of a certain (ViewModel) type to be draggable.
private void Grid_Drop(object sender, DragEventArgs e)
{
if (sender is FrameworkElement)
{
var fe = sender as FrameworkElement;
var targetIvm = fe.DataContext as ItemViewModel;
object obj = null;
if(e.DataView.Properties.TryGetValue("ItemViewModel", out obj))
{
var sourceIvm = obj as ItemViewModel;
vm.MoveItem(sourceIvm, targetIvm);
}
}
}
private void Grid_DragStarting(Windows.UI.Xaml.UIElement sender, DragStartingEventArgs args)
{
if (sender is FrameworkElement)
{
var fe = sender as FrameworkElement;
var item = new KeyValuePair<string, object>("ItemViewModel", fe.DataContext);
args.Data.RequestedOperation = DataPackageOperation.Move;
args.Data.Properties.Add("ItemViewModel", fe.DataContext);
}
}
I had the same issue please check this example I used Behaviors because I used MVVM pattern but I did this for ListView but is the same for GridView with small changes.
Change the Behaviors <ListView> to <GridView>
This behavior is attached in the ListView where you want drag the item
public class StartingDragBehavior:Behavior<ListView>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.CanDragItems = true;
this.AssociatedObject.DragItemsStarting += AssociatedObject_DragItemsStarting;
}
private void AssociatedObject_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
e.Data.RequestedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
if(e.Items!=null && e.Items.Any())
{
e.Data.Properties.Add("item", e.Items.FirstOrDefault());
}
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.DragItemsStarting -= AssociatedObject_DragItemsStarting;
}
}
This behavior is attached in the ListView where you want to drop the item
Here another Behavior to catch the drop event.
public class EndDropBehavior : Behavior<ListView>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.AllowDrop = true;
this.AssociatedObject.Drop += AssociatedObject_Drop;
this.AssociatedObject.DragOver += AssociatedObject_DragOver;
}
private void AssociatedObject_Drop(object sender, Windows.UI.Xaml.DragEventArgs e)
{
if (e.DataView != null &&
e.DataView.Properties != null &&
e.DataView.Properties.Any(x => x.Key == "item" && x.Value.GetType() == typeof(MyObject)))
{
try
{
var def = e.GetDeferral();
var item = e.Data.Properties.FirstOrDefault(x => x.Key == "item");
var card = item.Value as MyObject;
var list = sender as ListView;
var vm = list.DataContext as Infrastructure.ViewModels.CreditCardsViewModel;
vm.MyCollection.Add(card);
def.Complete();
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
else
{
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.None;
}
}
private void AssociatedObject_DragOver(object sender, Windows.UI.Xaml.DragEventArgs e)
{
if (e.DataView != null &&
e.DataView.Properties != null &&
e.DataView.Properties.Any(x => x.Key == "item" && x.Value.GetType() == typeof(MyObject)))
{
e.AcceptedOperation = e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
}
else
{
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.None;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.Drop -= AssociatedObject_Drop;
this.AssociatedObject.DragOver -= AssociatedObject_DragOver;
}
}
If you are not using MVVM pattern just check the events of the to Behaviors.

Capture user click and typing in a custom WPF TextBox-like control?

Trying to make an equation editor like that in Microsoft Word in C# and WPF. XML cannot be used; it has to be purely programmatic.
Right now I have LineGUIObject : System.Windows.Controls.WrapPanel, which is like System.Windows.Controls.TextBox, except that instead of just showing strings it shows each element of a List<System.Windows.UIElement> in order.
Now I want for a user to be able to click on an instance of LineGUIObject and type into it. The holdup is that I don't know how to capture the user's click or read the input that they type. How can this be done?
Note: This question is not asking how to handle input once captured; just how to get the input in the first place. For example, is there some event that fires off after the user clicks it or something? I can't seem to find one for System.Windows.Controls.WrapPanel, which might imply that I need to use another type of object, or..?
Current code:
public class LineGUIObject
: System.Windows.Controls.WrapPanel
{
private List<System.Windows.UIElement> _uiElementList;
private CursorGUIObject _cursor;
private int? _cursorIndex;
public LineGUIObject(System.Windows.Threading.Dispatcher dispatcher)
: base()
{
this.UIElementList = new List<System.Windows.UIElement>();
this.Cursor = new CursorGUIObject(dispatcher, 25, 1.5, 250);
this.UIElementList.Add(this.Cursor);
this.AddText("[junk string just to see this otherwise invisible object while debugging]");
}
protected void InterpretUserKeyStroke(/* ??? */)
{
//How do we get this method to be called on user input,
//e.g. when the user types "1"?
throw new NotImplementedException();
}
protected void AddText(string text)
{
this.UIElementList.Add(new System.Windows.Controls.TextBlock(new System.Windows.Documents.Run(text)));
this.UpdateDisplay();
}
protected List<System.Windows.UIElement> UIElementList { get { return this._uiElementList; } private set { this._uiElementList = value; } }
protected CursorGUIObject Cursor { get { return this._cursor; } private set { this._cursor = value; } }
protected int? CursorIndex
{
get { return this._cursorIndex; }
set
{
int? nullablePriorIndex = this.CursorIndex;
if (nullablePriorIndex != null)
{
int priorIndex = nullablePriorIndex.Value;
this.UIElementList.RemoveAt(priorIndex);
}
if (value == null)
{
this._cursorIndex = null;
}
else
{
int newIndex = value.Value;
if (newIndex < 0)
{
newIndex = 0;
}
else
{
int thisListCount = this.UIElementList.Count;
if (newIndex > thisListCount) { newIndex = thisListCount; }
}
this.UIElementList.Insert(newIndex, this.Cursor);
this._cursorIndex = newIndex;
}
this.UpdateDisplay();
}
}
protected void UpdateDisplay()
{
this.Children.Clear();
foreach (System.Windows.UIElement uiElement in this.UIElementList) { this.Children.Add(uiElement); }
}
}
public class CursorGUIObject
: System.Windows.Controls.WrapPanel
{
public const double MINIMUM_BLINK_TIME_IN_MS = 5;
public const double MINIMUM_HEIGHT = 0.5;
public const double MINIMUM_WIDTH = 0.5;
private object ToggleVisibilityLock = new object();
private delegate void TimerIntervalDelegate();
private System.Windows.Shapes.Rectangle _rectangle;
private System.Timers.Timer _timer;
private System.Windows.Threading.Dispatcher _dispatcher;
public CursorGUIObject(System.Windows.Threading.Dispatcher dispatcher, double height, double width, double blinkTimeInMS)
{
this.Dispatcher = dispatcher;
System.Windows.Shapes.Rectangle rectangle = new System.Windows.Shapes.Rectangle();
rectangle.Width = width > MINIMUM_WIDTH ? width : MINIMUM_WIDTH;
rectangle.Height = height > MINIMUM_HEIGHT ? height : MINIMUM_HEIGHT;
rectangle.Fill = System.Windows.Media.Brushes.Black;
this.Rectangle = rectangle;
this.Children.Add(rectangle);
System.Timers.Timer timer = new System.Timers.Timer(blinkTimeInMS > MINIMUM_BLINK_TIME_IN_MS ? blinkTimeInMS : MINIMUM_BLINK_TIME_IN_MS);
this.Timer = timer;
timer.Elapsed += timer_Elapsed;
timer.Start();
}
~CursorGUIObject()
{
System.Timers.Timer timer = this.Timer;
if (timer != null) { timer.Dispose(); }
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Delegate timerDelegate = new TimerIntervalDelegate(ToggleVisibility);
this.Dispatcher.BeginInvoke(timerDelegate);
}
protected void ToggleVisibility()
{
lock (ToggleVisibilityLock)
{
if (this.Rectangle.Visibility.Equals(System.Windows.Visibility.Hidden))
{
this.Rectangle.Visibility = System.Windows.Visibility.Visible;
}
else
{
this.Rectangle.Visibility = System.Windows.Visibility.Hidden;
}
}
}
protected System.Windows.Shapes.Rectangle Rectangle { get { return this._rectangle; } private set { this._rectangle = value; } }
protected System.Timers.Timer Timer { get { return this._timer; } private set { this._timer = value; } }
protected System.Windows.Threading.Dispatcher Dispatcher { get { return this._dispatcher; } private set { this._dispatcher = value; } }
}
Pretty much all WPF controls provide access to the UIElement.PreviewMouseDown Event, which you can use to monitor mouse clicks. So, this event lets you monitor when each object is clicked on. Next, I'd advise you to use a small Popup control to popup a TextBox that the user could enter a value with:
<Popup Name="Popup">
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="5" Padding="5">
<TextBox Text="{Binding InputText}" />
</Border>
</Popup>
Depending on how you have set up your project, you could open the Popup from the event handler:
private void YourObject_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
Popup.IsOpen = true;
}
Turns out that LineGUIObject just needed to have this.Focusable = true; set in its constructor so that it could receive the keyboard's focus when clicked.
Now that it can be focused on, this.KeyUp += LineGUIObject_KeyUp; also in the constructor, and
protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
{
this.AddText(e.Key.ToString());
}
Even this had a problem at first since my LineGUIObject was nested in a ScrollViewer which kept stealing focus immediately after the LineGUIObject would receive it. This was fixed by making the ScrollViewer to be unable to get focus, i.e. <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Focusable="False"/>.

Categories