I'm trying to setting the focus for a certain UIElement dependency object from viewmodel and to do that I have written an Attached Dependency Property as below:
#region IsFocusedProperty
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(AttachedProperties),
new FrameworkPropertyMetadata(false,
new PropertyChangedCallback(OnIsFocusedChanged)));
private static void OnIsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var obj = d as UIElement;
var oldValue = (bool)e.OldValue;
var newValue = (bool)e.NewValue;
if (oldValue != newValue && !obj.IsFocused)
{
obj.Focus();
}
}
public static void SetIsFoused(UIElement element, bool value)
{
element.SetValue(IsFocusedProperty, value);
}
public static bool GetIsFocused(UIElement element)
{
return (bool)element.GetValue(IsFocusedProperty);
}
#endregion
I should say it works and sends the focus to the specified element unless when I move the mouse cursor over each element in the view (including the specified element on which the focus is) no mouse event fires. I'm saying this because I've written triggers for IsMouseOverProperty of the elements but nothings happen when the focus is sent to the specified element in that way.
I should also say that the triggers works fine again when I click anywhere on the view. I really don't know what the problem is? please share your ideas. any idea would be appreciated. thanks in advance.
Edit:
I've figured it out that the element receives the keyboard focus but apparently not the logical focus because when I move the cursor to the previous element, it still fires MouseMove event.
I'm still not sure what the problem is?
Update to:
if (oldValue != newValue && !obj.IsFocused)
{
Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(delegate()
{
obj.Focus();
Keyboard.Focus(obj);
})
);
}
Related
I am having a bit of difficulty in a CRUD form. We have a button which saves the form and has the IsDefault flag set to true, so that the user can press enter at any point to save the form.
The problem is that when the user is typing in a textbox and hits the enter key the source of the textbox binding isn't updated. I know that this is because the default UpdateSourceTrigger functionality for textboxes is LostFocus, which I've used to overcome the problem is some cases, but this actually causes more problems in other cases.
For standard string fields this is fine, however for things like doubles and ints the validation occurs on property change, and so stop the user from typing say 1.5 into a textbox that is bound to a double source (they can type 1, but the validation stops the decimal, they could type 15 then move the cursor back and press . though).
Is there a better way to approach this? I looked at ways to refresh all bindings in the window in code which came up with firing a PropertyChanged event with string.empty however this only refreshes the target, not the source.
My standard solution when I don't want to set the UpdateSourceTrigger=PropertyChanged on the bindings is to use a custom AttachedProperty that when set to true will will update the source of the binding when Enter is pressed.
Here's a copy of my Attached Property
// When set to True, Enter Key will update Source
#region EnterUpdatesTextSource DependencyProperty
// Property to determine if the Enter key should update the source. Default is False
public static readonly DependencyProperty EnterUpdatesTextSourceProperty =
DependencyProperty.RegisterAttached("EnterUpdatesTextSource", typeof (bool),
typeof (TextBoxHelper),
new PropertyMetadata(false, EnterUpdatesTextSourcePropertyChanged));
// Get
public static bool GetEnterUpdatesTextSource(DependencyObject obj)
{
return (bool) obj.GetValue(EnterUpdatesTextSourceProperty);
}
// Set
public static void SetEnterUpdatesTextSource(DependencyObject obj, bool value)
{
obj.SetValue(EnterUpdatesTextSourceProperty, value);
}
// Changed Event - Attach PreviewKeyDown handler
private static void EnterUpdatesTextSourcePropertyChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs e)
{
var sender = obj as UIElement;
if (obj != null)
{
if ((bool) e.NewValue)
{
sender.PreviewKeyDown += OnPreviewKeyDownUpdateSourceIfEnter;
}
else
{
sender.PreviewKeyDown -= OnPreviewKeyDownUpdateSourceIfEnter;
}
}
}
// If key being pressed is the Enter key, and EnterUpdatesTextSource is set to true, then update source for Text property
private static void OnPreviewKeyDownUpdateSourceIfEnter(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (GetEnterUpdatesTextSource((DependencyObject) sender))
{
var obj = sender as UIElement;
BindingExpression textBinding = BindingOperations.GetBindingExpression(
obj, TextBox.TextProperty);
if (textBinding != null)
textBinding.UpdateSource();
}
}
}
#endregion //EnterUpdatesTextSource DependencyProperty
And it's used like this:
<TextBox Text="{Binding SomeText}" local:EnterUpdatesTextSource="True" />
You can update binding source by using the following code:
textBox1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
I'm trying to show a vertical line in position X of the cursor. I'm trying to do that in a slider control, but I couldn't made it. This will be showed while the user has its cursor on it.
I only know that I need to modify the template. Is so much difficult to do that? If not, can you help me?
Thanks.
This is not easy to attain using templating because of the fact that mouse position is not a dependency property and mouse move is not a routed event. This really comes down to what you want to do, if it's to just show a vertical line whether the mouse is then I agree with Dany to use adorners, as you're not really interested in the slider itself. However, if it's to move the thumb to where the mouse is I would use an attached property.
The reason I use attached properties rather than hooking up the events directly on the control is that it provides more modularised and reusable codebase and makes it more obvious of the visual effect in the XAML, rather than needing to look at C# code as well.
Here's what I would suggest
public class SliderHelperPackage
{
public static readonly DependencyProperty BindThumbToMouseProperty = DependencyProperty.RegisterAttached(
"BindThumbToMouse", typeof(bool), typeof(SliderHelperPackage), new PropertyMetadata(false, OnBindThumbToMouseChanged));
public static void SetBindThumbToMouse(UIElement element, bool value)
{
element.SetValue(BindThumbToMouseProperty, value);
}
public static bool GetBindThumbToMouse(UIElement element)
{
return (bool)element.GetValue(BindThumbToMouseProperty);
}
private static void OnBindThumbToMouseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue.Equals(e.OldValue))
return;
var slider = d as Slider;
if (slider == null)
throw new ArgumentException(#"dependency object must be a slider", "d");
if ((bool) e.NewValue)
{
slider.MouseMove += SliderMouseMove;
}
else
{
slider.MouseMove -= SliderMouseMove;
}
}
static void SliderMouseMove(object sender, MouseEventArgs e)
{
var slider = (Slider) sender;
var position = e.GetPosition(slider);
// When the mouse moves, we update the slider's value so it's where the ticker is (we take into account margin's on the track)
slider.Value = (slider.Maximum - slider.Minimum)*Math.Max(position.X-5,0)/(slider.ActualWidth-10) + slider.Minimum;
}
}
And you can then use it in your XAML like so. So when you set this to true we hook up to the mouse move event on the slider and change its value so the thumb follows the mouse
<Slider SliderPosn:SliderHelperPackage.BindThumbToMouse="True" Margin="5" Height="25" VerticalAlignment="Top"/>
http://www.codeproject.com/KB/WPF/adornedcontrol.aspx
this reference should give you all necessary information to fix your issue
cheers!
I'm trying to achieve an effect where more items are appended to the list when the user scrolls down to the last item. I haven't found a way to determine if the user has scrolled to the end of the list. I don't see a event on ListBox that is fired when the user reaches the bottom of the list. Something that tells me when an item has been scrolled into view would be great, but as far as I can tell, there is nothing like that.
Is this even possible in WP7?
Edit: Another way of saying this is, can we detect when a list has "bounced"?
Daniel Vaughan has posted an example of how to detect for this at http://danielvaughan.orpius.com/post/Scroll-Based-Data-Loading-in-Windows-Phone-7.aspx
It isn't super easy to get going since there are a lot of moving parts, but here is what you can do, assuming you want a short list that loads more from your data as you get scrolling down, similar to a lot of twitter apps, etc.
Write your own subclass of ObservableCollection that only offers up a few items (like 20), keeping the rest held back until requested
Hook up to the scroll viewer (inside the listbox or container) and its visual state changed events, you can get the NotScrolling and Scrolling changes; for an example see this code by ptorr
When scrolling stops, use viewer scroll extensions code to see where things are extended (at the bottom or not) or just the raw scroll viewer properties to see if it is extended to the bottom
If so, trigger your observable collection to release another set of items.
Sorry I don't have a complete sample ready to blog yet. Good luck!
I've just implemented this for Overflow7.
The approach I took was similar to http://blog.slimcode.com/2010/09/11/detect-when-a-listbox-scrolls-to-its-end-wp7/
However, instead of using a Style I did the hook up in code.
Basically derived my parent UserControl from:
public class BaseExtendedListUserControl : UserControl
{
DependencyProperty ListVerticalOffsetProperty = DependencyProperty.Register(
"ListVerticalOffset",
typeof(double),
typeof(BaseExtendedListUserControl),
new PropertyMetadata(new PropertyChangedCallback(OnListVerticalOffsetChanged)));
private ScrollViewer _listScrollViewer;
protected void EnsureBoundToScrollViewer()
{
if (_listScrollViewer != null)
return;
var elements = VisualTreeHelper.FindElementsInHostCoordinates(new Rect(0,0,this.Width, this.Height), this);
_listScrollViewer = elements.Where(x => x is ScrollViewer).FirstOrDefault() as ScrollViewer;
if (_listScrollViewer == null)
return;
Binding binding = new Binding();
binding.Source = _listScrollViewer;
binding.Path = new PropertyPath("VerticalOffset");
binding.Mode = BindingMode.OneWay;
this.SetBinding(ListVerticalOffsetProperty, binding);
}
public double ListVerticalOffset
{
get { return (double)this.GetValue(ListVerticalOffsetProperty); }
set { this.SetValue(ListVerticalOffsetProperty, value); }
}
private static void OnListVerticalOffsetChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
BaseExtendedListUserControl control = obj as BaseExtendedListUserControl;
control.OnListVerticalOffsetChanged();
}
private void OnListVerticalOffsetChanged()
{
OnListVerticalOffsetChanged(_listScrollViewer);
}
protected virtual void OnListVerticalOffsetChanged(ScrollViewer s)
{
// do nothing
}
}
this then meant that in the user control itself I could just use:
protected override void OnListVerticalOffsetChanged(ScrollViewer viewer)
{
// Trigger when at the end of the viewport
if (viewer.VerticalOffset >= viewer.ScrollableHeight)
{
if (MoreClick != null)
{
MoreClick(this, new RoutedEventArgs());
}
}
}
private void ListBox1_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
EnsureBoundToScrollViewer();
}
The "hacky" thing here was that I had to use ListBox1_ManipulationCompleted and VisualTreeHelper to find my ScrollViewer - I'm sure there are better ways...
Have a look at this detect Listbox compression state from msdn blog
Use the DeferredLoadListBox.
I am trying to set the initial focus to a control in a Silverlight form. I am trying to use attached properties so the focus can be specified in the XAML file. I suspect that the focus is being set before the control is ready to accept focus. Can anyone verify this or suggest how this technique might be made to work?
Here is my XAML code for the TextBox
<TextBox x:Name="SearchCriteria" MinWidth="200" Margin ="2,2,6,2" local:AttachedProperties.InitialFocus="True"></TextBox>
The property is defined in AttachedProperties.cs:
public static DependencyProperty InitialFocusProperty =
DependencyProperty.RegisterAttached("InitialFocus", typeof(bool), typeof(AttachedProperties), null);
public static void SetInitialFocus(UIElement element, bool value)
{
Control c = element as Control;
if (c != null && value)
c.Focus();
}
public static bool GetInitialFocus(UIElement element)
{
return false;
}
When I put a breakpoint in the SetInitialFocus method, it does fire and the control is indeed the desired TextBox and it does call Focus.
I know other people have created behaviors and such to accomplish this task, but I am wondering why this won't work.
You're right, the Control isn't ready to recieve focus because it hasn't finished loading yet. You can add this to make it work.
public static void SetInitialFocus(UIElement element, bool value)
{
Control c = element as Control;
if (c != null && value)
{
RoutedEventHandler loadedEventHandler = null;
loadedEventHandler = new RoutedEventHandler(delegate
{
// This could also be added in the Loaded event of the MainPage
HtmlPage.Plugin.Focus();
c.Loaded -= loadedEventHandler;
c.Focus();
});
c.Loaded += loadedEventHandler;
}
}
(In some cases, you may need to call ApplyTemplate as well according to this link)
enter code hereI have a ScrollViewer in Silverlight that is not scrolling vertically whenever I call the ScrollToVerticalOffset method from the code behind.
Basically, I have my View (UserControl) that contains the ScrollViewer. I invoke an action from my ViewModel that triggers an event in the View's code-behind that sets the VerticalOffset to a specific value.
First of all, I know this is very ugly. Ideally I wish that I could have an attachable property that I could bind to a property in my ViewModel, that, when set, would cause the VerticalOffset property (which I know is read-only) to be updated, and the ScrollViewer to scroll.
The ScrollViewer contains dynamic content. So, if the user is viewing content in the ScrollViewer, and scrolls half-way down, and then clicks on a button, new content is loaded into the ScrollViewer. The problem is that the ScrollViewer's vertical offset doesn't get reset, so the user has to scroll up to read the content. So, my solution was to be able to control the vertical offset from the ViewModel, and I have racked my brain and can't come up with a viable solution, so I am looking for someone to help, please.
By the way - I have included code from a class I put together for an attachable property. This property binds to a property in my ViewModel. When I set the property in the ViewModel, it correctly triggers the PropertyChanged callback method in this class, which then calls the ScrollToVerticalOffset method for the ScrollViewer, but the ScrollViewer still doesn't scroll.
public class ScrollViewerHelper
{
public static readonly DependencyProperty BindableOffsetProperty =
DependencyProperty.RegisterAttached("BindableOffset", typeof(double), typeof(ScrollViewerHelper),
new PropertyMetadata(OnBindableOffsetChanged));
public static double GetBindableOffset(DependencyObject d)
{
return (double)d.GetValue(BindableOffsetProperty);
}
public static void SetBindableOffset(DependencyObject d, double value)
{
d.SetValue(BindableOffsetProperty, value);
}
private static void OnBindableOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ScrollViewer scrollViewer = d as ScrollViewer;
if (scrollViewer != null)
{
scrollViewer.ScrollToVerticalOffset((double)e.NewValue);
}
}
}
This approach is a little bit funky in my opinion, as I think of both a ScrollViewer and a VerticalScrollOffset as "View" entities that should have very little (or nothing) to do with a ViewModel. It seems like this might be forcing MVVM a little too much, and creating a lot of extra work in creating an attached dependency property and basically trying to keep a bound Offset ViewModel property in sync with the readonly VerticalScrollOffset of the ScrollViewer.
I am not exactly sure of what you are trying to achieve, but it sounds like you are trying to scroll to a specified offset when some dynamic element is added to the underlying panel of your ScrollViewer. Personally, I would just want to handle this behavior with a little bit of code in my View and forget about tying it to the ViewModel.
One really nice way to do this type of thing in Silverlight 3 is with Blend behaviors. You write a little bit of behavior code in C# and then can attach it declaratively to an element in XAML. This keeps it reusable and out of your code-behind. Your project will have to reference the System.Windows.Interactivity DLL which is part of the Blend SKD.
Here's a simple example of a simple Blend behavior you could add to a ScrollViewer which scrolls to a specified offset whenever the size of the underlying content of the ScrollViewer changes:
public class ScrollToOffsetBehavior : Behavior<ScrollViewer>
{
private FrameworkElement contentElement = null;
public static readonly DependencyProperty OffsetProperty = DependencyProperty.Register(
"Offset",
typeof(double),
typeof(ScrollToOffsetBehavior),
new PropertyMetadata(0.0));
public double Offset
{
get { return (double)GetValue(OffsetProperty); }
set { SetValue(OffsetProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
if (this.AssociatedObject != null)
{
this.AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
}
}
protected override void OnDetaching()
{
base.OnDetaching();
if (this.contentElement != null)
{
this.contentElement.SizeChanged -= contentElement_SizeChanged;
}
if (this.AssociatedObject != null)
{
this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
}
}
void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
this.contentElement = this.AssociatedObject.Content as FrameworkElement;
if (this.contentElement != null)
{
this.contentElement.SizeChanged += new SizeChangedEventHandler(contentElement_SizeChanged);
}
}
void contentElement_SizeChanged(object sender, SizeChangedEventArgs e)
{
this.AssociatedObject.ScrollToVerticalOffset(this.Offset);
}
}
You could then apply this behavior to the ScrollViewer in XAML (and specify an offset of 0 to scroll back to the top):
<ScrollViewer>
<i:Interaction.Behaviors>
<local:ScrollToOffsetBehavior Offset="0"/>
</i:Interaction.Behaviors>
...Scroll Viewer Content...
</ScrollViewer>
This would be assuming that you always want to scroll to the offset whenever the content size changes. This may not be exactly what you are looking for, but it is one example of how something like this can be done in the view using a behavior.