Display ContextMenu on LongPress for a View in xamarin forms - xamarin.forms

Hi,
Could you please let me know how to display a context menu on long press effect.I have added a ListView with Effects but the context menu is not popping up after long pressing the listview.
MainPage.xaml
<ContentView x:Name="Parent" BackgroundColor="White" Padding="20" >
<dg:DataGrid ItemsSource="{Binding Data}" SelectionEnabled="True" RowHeight="70" HeaderHeight="50" BorderColor="#CCCCCC" HeaderBackground="#E0E6F8" ActiveRowColor="#8899AA">
<dg:DataGrid.Columns>
<dg:DataGridColumn Title="Logo" PropertyName="Logo" Width="50" SortingEnabled="False">
<dg:DataGridColumn.CellTemplate>
<DataTemplate>
<ListView x:Name="MainListView" local:LongPressedEffect.Command="{Binding ShowAlertCommand}" local:LongPressedEffect.CommandParameter="{Binding .}">
<ListView.Effects>
<local:LongPressedEffect />
</ListView.Effects>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Text="Add" ></MenuItem>
<MenuItem Text="Delete" ></MenuItem>
<MenuItem Text="Edit" ></MenuItem>
</ViewCell.ContextActions>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</dg:DataGridColumn.CellTemplate>
</dg:DataGridColumn>
<dg:DataGridColumn Title="Team" PropertyName="Name" Width="2*" >
</dg:DataGridColumn>
<dg:DataGridColumn Title="Win" PropertyName="Win" Width="2*">
<dg:DataGridColumn.CellTemplate>
<DataTemplate>
<Picker x:Name="Fruits" Title="Fruits" HorizontalOptions="FillAndExpand">
<Picker.Items>
<x:String>Apple</x:String>
<x:String>Orange</x:String>
</Picker.Items>
</Picker>
</DataTemplate>
</dg:DataGridColumn.CellTemplate>
</dg:DataGridColumn>
<dg:DataGridColumn Title="Loose" PropertyName="Loose" Width="1*">
</dg:DataGridColumn>
<dg:DataGridColumn PropertyName="Home">
<dg:DataGridColumn.FormattedTitle>
<FormattedString>
<Span Text="Home" ForegroundColor="Black" FontSize="13" FontAttributes="Bold"/>
<Span Text=" (win-loose)" ForegroundColor="#333333" FontSize="11" />
</FormattedString>
</dg:DataGridColumn.FormattedTitle>
</dg:DataGridColumn>
<dg:DataGridColumn Title="Percentage" PropertyName="Percentage"/>
<dg:DataGridColumn Title="Streak" PropertyName="Streak" Width="0.7*"/>
</dg:DataGrid.Columns>
</ContentView>
LongPressedEffect.cs
public class LongPressedEffect : RoutingEffect
{
public LongPressedEffect() : base("MyApp.LongPressedEffect")
{
}
public static readonly BindableProperty CommandProperty = BindableProperty.CreateAttached("Command", typeof(ICommand), typeof(LongPressedEffect), (object)null);
public static ICommand GetCommand(BindableObject view)
{
return (ICommand)view.GetValue(CommandProperty);
}
public static void SetCommand(BindableObject view, ICommand value)
{
view.SetValue(CommandProperty, value);
}
public static readonly BindableProperty CommandParameterProperty = BindableProperty.CreateAttached("CommandParameter", typeof(object), typeof(LongPressedEffect), (object)null);
public static object GetCommandParameter(BindableObject view)
{
return view.GetValue(CommandParameterProperty);
}
public static void SetCommandParameter(BindableObject view, object value)
{
view.SetValue(CommandParameterProperty, value);
}
}
AndroidLongPressedEffect.cs
public class AndroidLongPressedEffect : PlatformEffect
{
private bool _attached;
/// <summary>
/// Initializer to avoid linking out
/// </summary>
public static void Initialize() { }
/// <summary>
/// Initializes a new instance of the
/// <see cref="T:Yukon.Application.AndroidComponents.Effects.AndroidLongPressedEffect"/> class.
/// Empty constructor required for the odd Xamarin.Forms reflection constructor search
/// </summary>
public AndroidLongPressedEffect()
{
}
/// <summary>
/// Apply the handler
/// </summary>
protected override void OnAttached()
{
//because an effect can be detached immediately after attached (happens in listview), only attach the handler one time.
if (!_attached)
{
if (Control != null)
{
Control.LongClickable = true;
Control.LongClick += Control_LongClick;
}
else
{
Container.LongClickable = true;
Container.LongClick += Control_LongClick;
}
_attached = true;
}
}
/// <summary>
/// Invoke the command if there is one
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
private void Control_LongClick(object sender, Android.Views.View.LongClickEventArgs e)
{
Console.WriteLine("Invoking long click command");
var command = LongPressedEffect.GetCommand(Element);
command?.Execute(LongPressedEffect.GetCommandParameter(Element));
}
/// <summary>
/// Clean the event handler on detach
/// </summary>
protected override void OnDetached()
{
if (_attached)
{
if (Control != null)
{
Control.LongClickable = true;
Control.LongClick -= Control_LongClick;
}
else
{
Container.LongClickable = true;
Container.LongClick -= Control_LongClick;
}
_attached = false;
}
}
}
Any help is very much appreciated!
Please let me know if more information is required.

You can set a property in App.cs as currentPage.
public static ContentPage currentPage;
And set it in the contentPage which contains your listView.
public xxxPage()
{
InitializeComponent();
App.currentPage = this;
}
And in LongPressedEffect.cs
public static ICommand GetCommand(BindableObject view)
{
//do something you want
App.currentPage.DisplayActionSheet("ActionSheet: Send to?", "Cancel", null, "Email", "Twitter", "Facebook");
return (ICommand)view.GetValue(CommandProperty);
}

Related

Swipe Down To Close Popup not working with CarouselView in Xamarin

I am displaying a CarouselView inside a PopupPage (using Rg.Plugins.Popup). It has 2 problems that I don't understand yet:
1. I am trying to do Swipe Down To Close Popup feature. Everything works fine if my UI is just like this:
PopupOne.xaml
<popup:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:popup="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
.....
x:Class="xxx.Views.PopupImgProd">
<ContentView>
<ContentView.Behaviors>
<behavior:SwipeDownToClosePopupPage CloseAction="SwipeDownToClosePopupPage_CloseAction"
ClosingEdge="0"
ClosingTimeInMs="400"/>
</ContentView.Behaviors>
<StackLayout HorizontalOptions="FillAndExpand" Padding="0" BackgroundColor="#fff">
<AbsoluteLayout HorizontalOptions="FillAndExpand">
<Frame>
....
</Frame>
<Frame>
....
</Frame>
</AbsoluteLayout>
<Label Text="sss"/>
</StackLayout>
</ContentView>
</popup:PopupPage>
SwipeDownToClosePopupPage.cs
public class SwipeDownToClosePopupPage : Behavior<View>
{
private PanGestureRecognizer PanGestureRecognizer { get; set; }
private DateTimeOffset? StartPanDownTime { get; set; }
private DateTimeOffset? EndPanDownTime { get; set; }
private double TotalY { get; set; }
private bool ReachedEdge { get; set; }
/// <summary>
/// Close action, depends on your navigation mode
/// </summary>
public event Action CloseAction;
public static readonly BindableProperty ClosingEdgeProperty = BindableProperty.Create(propertyName: nameof(ClosingEdge)
, returnType: typeof(Double)
, declaringType: typeof(SwipeDownToClosePopupPage)
, defaultValue: Convert.ToDouble(100)
, defaultBindingMode: BindingMode.TwoWay
, propertyChanged: ClosingEdgePropertyChanged);
/// <summary>
/// The height from the bottom that will trigger close page
/// </summary>
public Double ClosingEdge
{
get { return (Double)GetValue(ClosingEdgeProperty); }
set { SetValue(ClosingEdgeProperty, Convert.ToDouble(value)); }
}
private static void ClosingEdgePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (SwipeDownToClosePopupPage)bindable;
if (newValue != null)
{
control.ClosingEdge = Convert.ToDouble(newValue);
}
}
public static readonly BindableProperty ClosingTimeInMsProperty = BindableProperty.Create(propertyName: nameof(ClosingTimeInMs)
, returnType: typeof(Int64)
, declaringType: typeof(SwipeDownToClosePopupPage)
, defaultValue: Convert.ToInt64(500)
, defaultBindingMode: BindingMode.TwoWay
, propertyChanged: ClosingTimeInMsPropertyChanged);
/// <summary>
/// Scroll time less than this value will trigger close page
/// </summary>
public Int64 ClosingTimeInMs
{
get { return (Int64)GetValue(ClosingTimeInMsProperty); }
set { SetValue(ClosingTimeInMsProperty, Convert.ToInt64(value)); }
}
private static void ClosingTimeInMsPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (SwipeDownToClosePopupPage)bindable;
if (newValue != null)
{
control.ClosingTimeInMs = Convert.ToInt64(newValue);
}
}
public SwipeDownToClosePopupPage()
{
this.PanGestureRecognizer = new PanGestureRecognizer();
}
protected override void OnAttachedTo(View v)
{
PanGestureRecognizer.PanUpdated += Pan_PanUpdated;
v.GestureRecognizers.Add(this.PanGestureRecognizer);
base.OnAttachedTo(v);
}
protected override void OnDetachingFrom(View v)
{
PanGestureRecognizer.PanUpdated -= Pan_PanUpdated;
v.GestureRecognizers.Remove(this.PanGestureRecognizer);
base.OnDetachingFrom(v);
}
private void Pan_PanUpdated(object sender, PanUpdatedEventArgs e)
{
View v = sender as View;
switch (e.StatusType)
{
case GestureStatus.Started:
StartPanDownTime = DateTime.Now;
break;
case GestureStatus.Running:
TotalY = e.TotalY;
if (TotalY > 0)
{
if (Device.RuntimePlatform == Device.Android)
{
v.TranslateTo(0, TotalY + v.TranslationY, 20, Easing.Linear);
//Too close to edge?
ReachedEdge = TotalY + v.TranslationY > v.Height - ClosingEdge;
}
else
{
v.TranslateTo(0, TotalY, 20, Easing.Linear);
//Too close to edge?
ReachedEdge = TotalY > v.Height - ClosingEdge;
}
}
break;
case GestureStatus.Completed:
EndPanDownTime = DateTimeOffset.Now;
if (TotalY > 0
|| ReachedEdge)
//Swipe too fast
CloseAction?.Invoke();
else
{
v.TranslateTo(0, 0, 20, Easing.Linear);
}
break;
}
if (e.StatusType == GestureStatus.Completed || e.StatusType == GestureStatus.Canceled)
{
StartPanDownTime = null;
EndPanDownTime = null;
}
}
}
----------> The above it works great. When I SwipeDown it closes the Popup. Very good
However, now what I display is: CarouselView.
The problem occurs here: When I SwipeDown it doesn't close the Popup? Even though I have wrapped the event for it as it was at the beginning.
PopupOne.xaml
<popup:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:popup="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
.....
x:Class="TopSell.Views.PopupImgProd">
<ContentView>
<ContentView.Behaviors>
<behavior:SwipeDownToClosePopupPage CloseAction="SwipeDownToClosePopupPage_CloseAction"
ClosingEdge="0"
ClosingTimeInMs="400"/>
</ContentView.Behaviors>
<StackLayout HorizontalOptions="FillAndExpand" Padding="0" BackgroundColor="#fff">
<AbsoluteLayout HorizontalOptions="FillAndExpand">
<Frame>
....
</Frame>
<Frame>
....
</Frame>
</AbsoluteLayout>
<CarouselView x:Name="_stdata" ItemsSource="{Binding imglistProd}">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout Padding="0" Margin="0" VerticalOptions="FillAndExpand" x:DataType="model:ProductImages">
<Image Aspect="AspectFill" VerticalOptions="CenterAndExpand" Source="{Binding Images}"/>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</StackLayout>
</ContentView>
</popup:PopupPage>
PopupOne.xaml.cs
private void SwipeDownToClosePopupPage_CloseAction()
{
PopupNavigation.Instance.PopAllAsync();
}
---> Is there a conflict between the left and right movement of CarouselView and SwipeDown
2. The displayed image of the CarouselView seems to cut off the top and bottom of the image (Image is cropped when I put it in CarouselView )
Looking forward to everyone's help. Thank you

How to access the BindingContext of custom control in Xamarin.Forms

I have a CollectionView with ItemsSource set to ObservableCollection of type Employee.
The ItemTemplate of the CollectionView is a CustomControl that has 1 BindableProperty of Type Employee
MainPage.xaml:
<CollectionView ItemsSource="{Binding Employees}"
SelectedItem="{Binding SelectedEmployee}">
<CollectionView.ItemTemplate>
<DataTemplate>
<controls:CustomControl Employee="{Binding .}" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
The CustomControl has an image (checked image to indicate selection).
CustomControl.xaml:
<Frame HasShadow="True"
BackgroundColor="Blue">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Image Source="check.png" />
</StackLayout>
</Frame>
CustomControl.xaml.cs:
public partial class CustomControl : ContentView
{
public CustomControl()
{
InitializeComponent();
}
public static BindableProperty EmployeeProperty = BindableProperty.Create(
propertyName: nameof(Employee),
returnType: typeof(Employee),
declaringType: typeof(CustomControl),
defaultValue: default(Employee),
defaultBindingMode: BindingMode.OneWay);
public Employee Employee
{
get
{
return (Employee)GetValue(EmployeeProperty);
}
set
{
SetValue(EmployeeProperty, value);
}
}
}
Model (Employee):
public class Employee: INotifyPropertyChanged
{
private int name;
public int Name
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged(nameof(Name));
}
}
private int isSelected;
public int IsSelected
{
get
{
return isSelected;
}
set
{
isSelected = value;
OnPropertyChanged(nameof(IsSelected));
}
}
#region PropertyChanged
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
I am trying to create simple animation (FadeIn/FadeOut) for the checked image in the CustomControl so when an item is selected the image will fade in, and when unselected it will fade out. I could use IsVisible and set it to true/false but that's ugly.
My idea was to listen to PropertyChanged event of the Employee (which supposed to be the context of my CustomControl), and when the property IsSelected is modified, I will start the animation to show/hide the image. something like this
public CustomControl()
{
InitializeComponent();
(this.BindingContext as Employee).PropertyChanged += CustomControl_PropertyChanged;
}
private void CustomControl_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Employee.IsSelected))
{
//do animation to show/hide image
}
}
But couldn't access the Context of my CustomControl!
When I declare the binding in MainPage.xaml I am passing a single Emplyee objet as BindingContext (that dot, right?):
<controls:CustomControl Employee="{Binding .}" />
but after the CustomControl is initializd, the BindingContext is still null!
public CustomControl()
{
InitializeComponent();
var context = this.BindingContext; //this is null
}
How can I observe the changes on the IsSelected property of the Employee object from my CustomControl?
In your custom control override the OnBindingContextChanged method, inside of that method you should be able to access the binding context that is set for your view.
Ex:
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
var context = this.BindingContext as Employee
}

Steps to create a behavior (how create a behavior)

i need to create a behavior from a view, i am using a class, also namespace to call to behavior but it's not working for me, i do not know what is my wrong, because i am doing all of step to create a behavior.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Layouts.Commands.BasketView"
xmlns:local="clr-namespace:Layouts;assembly=Layouts"
Title="Cart">
<StackLayout Padding="10,60,10,0">
<Label Text="Red when the number isn't valid" FontSize="Small" />
<Entry Placeholder="Enter a System.Double"
local:NumericValidationBehavior.AttachBehavior="true" />
</StackLayout>
</ContentPage>
in this line i get the error local:NumericValidationBehavior.AttachBehavior="true" />
i have my behavior, but it cannot be instanciate in the view (see code up), there are other step to be instanciate?
namespace AttachedNumericValidationBehavior
{
public static class NumericValidationBehavior
{
public static readonly BindableProperty AttachBehaviorProperty
= BindableProperty.CreateAttached("AttachBehavior", typeof(bool), typeof(NumericValidationBehavior), false, propertyChanged: OnAttachBehaviorChanged);
public static bool GetAttachBehavior(BindableObject view)
{
return (bool)view.GetValue(AttachBehaviorProperty);
}
public static void SetAttachBehavior(BindableObject view, bool value)
{
view.SetValue(AttachBehaviorProperty, value);
}
static void OnAttachBehaviorChanged(BindableObject view, object oldValue, object newValue)
{
var entry = view as Entry;
if (entry == null)
{
return;
}
bool attachBehavior = (bool)newValue;
if (attachBehavior)
{
entry.TextChanged += OnEntryTextChanged;
}
else
{
entry.TextChanged -= OnEntryTextChanged;
}
}
static void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
double result;
bool isValid = double.TryParse(args.NewTextValue, out result);
((Entry)sender).TextColor = isValid ? Color.Default : Color.Red;
}
}
}
the error is: "AttachBehavior is not in type NumericValidationBehavior"
You class NumericValidationBehavior belongs to namespace AttachedNumericValidationBehavior, so when you want to use NumericValidationBehavior in xaml, the namespace local should be:
xmlns:local="clr-namespace:AttachedNumericValidationBehavior;"
And use the namespace:
<StackLayout Padding="10,60,10,0">
<Label Text="Red when the number isn't valid" FontSize="Small" />
<Entry Placeholder="Enter a System.Double"
local:NumericValidationBehavior.AttachBehavior="true" />
</StackLayout>
For more details, see document: Declaring Namespaces for Types

Xamarin Forms how to add behaviors to custom control

I have created a custom control,which is a ContentView with a Label and an Entry
The xaml of the custom controls looks like this:
<Label Text="{Binding Source={x:Reference ValidationControl}, Path=Caption}"/>
<Entry Text="{Binding Source={x:Reference ValidationControl}, Path=Value, Mode=TwoWay}" />
The code behind of the custom control looks like this:
public static readonly BindableProperty CaptionProperty = BindableProperty.Create(
nameof(Caption), typeof(string), typeof(ValidationEntry), default(string));
public string Caption
{
get => (string)GetValue(CaptionProperty);
set => SetValue(CaptionProperty, value);
}
public static readonly BindableProperty ValueProperty = BindableProperty.Create(
nameof(Value), typeof(string), typeof(ValidationEntry), default(string));
public string Value
{
get => (string)GetValue(ValueProperty);
set => SetValue(ValueProperty, value);
}
I’m using the custom control in the following way
<controls:ValidationEntry Caption=”Name:” Value="{Binding FullName, Mode=TwoWay}" />
My question is how to add behaviors to the custom control?
I would like to add them in the place that I’m using the control. i.e.
<controls:ValidationEntry Caption="Name:"
Value="{Binding FullName, Mode=TwoWay}">
<controls:ValidationEntry.EntryBehaviors>
<behaviors:EntryLengthValidatorBehavior IgnoreSpaces="True"/>
</controls:ValidationEntry.EntryBehaviors>
</controls:ValidationEntry>
You can create a behaviors directly, I add a NumericValidationBehavior in my custom entry to check the data if it is double.If type of the data is not double, the color of text will be set to red.
Here is xaml code.
<StackLayout>
<local:MyEntry local:NumericValidationBehavior.AttachBehavior="true">
</local:MyEntry>
</StackLayout>
Here is NumericValidationBehavior.cs
public static class NumericValidationBehavior
{
public static readonly BindableProperty AttachBehaviorProperty =
BindableProperty.CreateAttached(
"AttachBehavior",
typeof(bool),
typeof(NumericValidationBehavior),
false,
propertyChanged: OnAttachBehaviorChanged);
public static bool GetAttachBehavior(BindableObject view)
{
return (bool)view.GetValue(AttachBehaviorProperty);
}
public static void SetAttachBehavior(BindableObject view, bool value)
{
view.SetValue(AttachBehaviorProperty, value);
}
static void OnAttachBehaviorChanged(BindableObject view, object oldValue, object newValue)
{
var entry = view as Entry;
if (entry == null)
{
return;
}
bool attachBehavior = (bool)newValue;
if (attachBehavior)
{
entry.TextChanged += OnEntryTextChanged;
}
else
{
entry.TextChanged -= OnEntryTextChanged;
}
}
static void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
double result;
bool isValid = double.TryParse(args.NewTextValue, out result);
((Entry)sender).TextColor = isValid ? Color.Default : Color.Red;
}
}
Update
I create a custom view with ContentView
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="BeHavDemo.MyView">
<ContentView.Content>
<StackLayout>
<Label Text="xxxx"/>
<Entry Text="eeeee" />
</StackLayout>
</ContentView.Content>
</ContentView>
Then I create a behavior.
public class MyBeha : Behavior<MyView>
{
protected override void OnAttachedTo(BindableObject view)
{
base.OnAttachedTo(view);
var myview=view as MyView;
StackLayout stackLayout = (StackLayout)myview.Content;
Label label = (Label)stackLayout.Children[0];
Entry entry=(Entry) stackLayout.Children[1];
}
}

Dynamic binding with User Control does not work as Static is working in Silverlight and MVVM

I have created sample User Control
RestrictedBox.xaml
<UserControl.Resources>
<Converters:EnumToVisibilityConverter x:Key="enumToVisConverter" />
<Converters:EnumToVisibilityConverterReverse x:Key="enumToVisConverterReverse" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" Width="Auto">
<StackPanel Margin="0">
<TextBox Text="{Binding Value}" Visibility="{Binding Type,Converter={StaticResource enumToVisConverter}}" BorderBrush="Green" />
<PasswordBox Password="{Binding Value}" Visibility="{Binding Type,Converter={StaticResource enumToVisConverterReverse}}" BorderBrush="Red" />
</StackPanel>
</Grid>
RestrictedBox.xaml.cs
public partial class RestrictedBox : UserControl
{
public RestrictedBox()
{
InitializeComponent();
//If i bind static value and uncomment following line then it is working.
//If i bind static value and comment following line then it is not working
this.DataContext = this;
//Dynamic binding does not work using this code.
}
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(RestrictedBox), new PropertyMetadata("", ValueChanged));
private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
public Mode Type
{
get { return (Mode)GetValue(TypeProperty); }
set { SetValue(TypeProperty, value); }
}
public static readonly DependencyProperty TypeProperty = DependencyProperty.Register("Type", typeof(Mode), typeof(RestrictedBox), new PropertyMetadata(TypeChanged));
private static void TypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
}
LoginViewModel.cs
public class LoginViewModel : INotifyPropertyChanged, IRegionMemberLifetime
{
private string _UserName = "Imdadhusen Sunasara";
public string UserName
{
get { return _UserName; }
set
{
_UserName = value;
OnPropertyChanged("UserName");
}
}
}
LoginView.xaml (This following line does not work with binding)
<control:RestrictedBox Value="{Binding UserName}" Type="Text" />
This is working (with static binding)
<control:RestrictedBox Value="Imdadhusen" Type="Text" />
Thanks,
Imdadhusen
Actually It should work. Can you please verify that the DataContext of parent container of below control doesn't refering to any other property of viewmodel.
<control:RestrictedBox Value="Imdadhusen" Type="Text" />
eg. Something like below.
<StackPanel DataContext={Binding CurrentUser}>
<control:RestrictedBox Value="{Binding UserName}"
Type="Text" />
</StackPanel>
May be this help you....
I have got solution from following
http://forums.silverlight.net/t/250206.aspx/1?Dynamic+binding+with+User+Control+does+not+work+as+Static+is+working+in+Silverlight+and+MVVM
Thanks everybody who trying to help me.
Imdadhusen

Resources