In wpf we should not access any UI control in viewmodel then how can we focus on control any such condition . below is solution for the same.
First create a attached property.
public static class FocusExt
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExt),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
uie.Focus();
}
}
}
First add namastace inb XAML like.
xmlns:utility="clr-namespace:NPOS.Utility"
then create a property in Model.
private bool isControlFocused;
public bool IsControlFocused
{
get { return isControlFocused; }
set { isControlFocused = value; OnPropertyChanged("IsControlFocused"); }
}
and set it to true in ViewModel.
Model.IsControlFocused = true;
and finally bind this property ib View.
<TextBox utility:FocusExt.IsFocused="{Binding Model.IsControlFocused}"/>
First create a attached property.
public static class FocusExt
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExt),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
uie.Focus();
}
}
}
First add namastace inb XAML like.
xmlns:utility="clr-namespace:NPOS.Utility"
then create a property in Model.
private bool isControlFocused;
public bool IsControlFocused
{
get { return isControlFocused; }
set { isControlFocused = value; OnPropertyChanged("IsControlFocused"); }
}
and set it to true in ViewModel.
Model.IsControlFocused = true;
and finally bind this property ib View.
<TextBox utility:FocusExt.IsFocused="{Binding Model.IsControlFocused}"/>
No comments:
Post a Comment