ItemsControl ItemsSource lazy loading - wpf

Image you are creating a custom control behaving like ComboBox in WPF.
As a source of items you provide IQueryable<T> (or any kind of IEnumerable collection),
but you don't want to allow the control to call GetIterator() and iterate through it (some kind of a lazy loading).
Let's say you inherit from the (because you want all the funcionality of that control)
System.Windows.Controls.Primitives.Selector
class.
The Selector class inherits from System.Windows.Controls.ItemsControl class which provides a the well known dependency property ItemsSource.
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(ItemsControl),
new FrameworkPropertyMetadata(null, new PropertyChangedCallback(ItemsControl.OnItemsSourceChanged)));
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsControl control = (ItemsControl) d;
IEnumerable oldValue = (IEnumerable) e.OldValue;
IEnumerable newValue = (IEnumerable) e.NewValue;
ItemValueStorageField.ClearValue(d);
if ((e.NewValue == null) && !BindingOperations.IsDataBound(d, ItemsSourceProperty))
{
control.Items.ClearItemsSource();
}
else
{
control.Items.SetItemsSource(newValue); // PROBLEM
}
control.OnItemsSourceChanged(oldValue, newValue);
}
If I see it correctly, this is the place where it iterates.
internal void SetItemsSource(IEnumerable value)
{
if ((!this.IsUsingItemsSource && (this._internalView != null)) && (this._internalView.RawCount > 0))
{
throw new InvalidOperationException(SR.Get("CannotUseItemsSource"));
}
this._itemsSource = value;
this._isUsingItemsSource = true;
this.SetCollectionView(CollectionViewSource.GetDefaultCollectionView(this._itemsSource, this.ModelParent));
}
So I've decided to override metadata of ItemsSourceProperty and point it to my own static method,
where I'm planing not co call SetItemsSource (rather delay it).
How should it be done in your opinion?
Thank you

Your best bet would be to probably add a new dependency property, say DelayedItemsSource of type IEnumerable. Then you could bind ItemsSource to DelayedItemsSource after your delay.

Related

How to destroy or detach a CollectionView

I observe an odd behaviour of WPF ItemsControls: If a set the ItemsSource to an object which implements INotifyCollectionChanged and after that set the ItemsSource to null, the CollectionView which was created to provide the data to the ItemsControl still listens to the CollectionChanged-event of the source object.
If now the source collection is changed through a different thread, the CollectionView throws an exception (without being attached to any control).
While I understand why this is happening, I’m really stuck resolving this situation.
Therefore the main question is, how can I destroy a CollectionView so that it does not listen any more to CollectionChanged-event. Or how can I disable it doing that / detaching the underlying collection.
Please note: The described behavior is not with ObservableCollection. The source object is an IEnumerable of T and implements INotifyCollectionChanged.
You're looking for the CollectionView.DetachFromSourceCollection() method:
var collectionView = CollectionViewSource.GetDefaultView(yourEnumerable) as CollectionView;
collectionView.DetachFromSourceCollection();
Update
It seems, that under .net 4.5 there is this desired functionality. See the answer of HighCore. For those not having 4.5 I leave my workaround here, maybe it helps someone:
class DetachableNotifyCollectionChangedWrapper : IEnumerable, INotifyCollectionChanged {
IEnumerable m_source;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public DetachableNotifyCollectionChangedWrapper(IEnumerable enumerable) {
if (null == enumerable) throw new ArgumentNullException("enumerable"); ;
m_source = enumerable;
var ncc = m_source as INotifyCollectionChanged;
if (null != ncc) ncc.CollectionChanged += SourceCollectionChanged;
}
void SourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
if (null != CollectionChanged) CollectionChanged(this,e);
}
public IEnumerator GetEnumerator() {
return m_source.GetEnumerator();
}
public void Detach() {
var ncc = m_source as INotifyCollectionChanged;
if (null != ncc) ncc.CollectionChanged -= SourceCollectionChanged;
}
}
To use this, set the Wrapper as the ItemsSource of the ItemsControl. Before setting then the ItemsSource to null, call Detach on the wrapper to unregister the changed-event. Something as follows:
var wrapper = m_lstLog.ItemsSource as DetachableNotifyCollectionChangedWrapper;
if (null != wrapper) wrapper.Detach();
m_lstLog.ItemsSource = null;
The wrapper can also be used from within a ViewModel.

PropertyChangedCallback fired before WPF attached behavior gets attached

I'm working with a custom WPF behavior (the one from System.Windows.Interactivity) showing a couple of dependency properties, one of those being a string. The behavior also overrides OnAttached in order to grab a reference to its AssociatedObject UI control.
When that attached property is data-bound to viewModel and is later changed (and notified) at some point, everything seems fine: OnAttached has been fired "at the beginning", and later the PropertyChangedCallback gets fired.
The issue I see is when the property is not bound, but set to a "static" value in XAML. In this case the PropertyChangedCallback gets fired before OnAttached, when the behavior has yet to know its associated UI control and basically cannot do anything in reaction to that property changing.
I guess I'm missing something on how things should be done in this case. Any help in understanding this is appreciated. TA
EDIT
Showing here some code, if that might be helpful in this case:
public class SomeUIControlBehaviour : Behavior<SomeUIControl>
{
protected override void OnAttached()
{
base.OnAttached();
_attachedUIControl = this.AssociatedObject;
}
protected override void OnDetaching()
{
base.OnDetaching();
_attachedUIControl = null;
}
private SomeUIControl _attachedUIControl;
private void MessageChanged()
{
if (_attachedUIControl != null)
{
// do something on it
}
else
{
// bummer!
}
}
// Text property + dependency property
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
private static string _defaultMessage = String.Empty;
// Using a DependencyProperty as the backing store for Message. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MessageProperty =
DependencyProperty.Register("Message",
typeof(string), typeof(SomeUIControlBehaviour),
new PropertyMetadata(_defaultMessage, MessagePropertyChanged));
private static void MessagePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs evt)
{
//Debug.WriteLine("MessagePropertyChanged, on " + sender.GetType().Name + ", to value " + evt.NewValue);
SomeUIControlBehaviour behaviour = sender as SomeUIControlBehaviour;
if (behaviour == null)
{
Debug.Fail("Message property should be used only with SomeUIControlBehaviour");
return;
}
behaviour.MessageChanged();
}
}
As per comment, one simple answer could be:
when behavior gets attached, just check if the property has already a value (maybe different than default) and in that case do what the PropertyChangedCallback was supposed to do.

Force Propagation of Coerced Value

tl;dr: Coerced values are not propagated across data bindings. How can I force the update across the data binding when code-behind doesn't know the other side of the binding?
I'm using a CoerceValueCallback on a WPF dependency property and I'm stuck at the issue that coerced values don't get propagated through to bindings.
Window1.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace CoerceValueTest
{
public class SomeControl : UserControl
{
public SomeControl()
{
StackPanel sp = new StackPanel();
Button bUp = new Button();
bUp.Content = "+";
bUp.Click += delegate(object sender, RoutedEventArgs e) {
Value += 2;
};
Button bDown = new Button();
bDown.Content = "-";
bDown.Click += delegate(object sender, RoutedEventArgs e) {
Value -= 2;
};
TextBlock tbValue = new TextBlock();
tbValue.SetBinding(TextBlock.TextProperty,
new Binding("Value") {
Source = this
});
sp.Children.Add(bUp);
sp.Children.Add(tbValue);
sp.Children.Add(bDown);
this.Content = sp;
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value",
typeof(int),
typeof(SomeControl),
new PropertyMetadata(0, ProcessValueChanged, CoerceValue));
private static object CoerceValue(DependencyObject d, object baseValue)
{
if ((int)baseValue % 2 == 0) {
return baseValue;
} else {
return DependencyProperty.UnsetValue;
}
}
private static void ProcessValueChanged(object source, DependencyPropertyChangedEventArgs e)
{
((SomeControl)source).ProcessValueChanged(e);
}
private void ProcessValueChanged(DependencyPropertyChangedEventArgs e)
{
OnValueChanged(EventArgs.Empty);
}
protected virtual void OnValueChanged(EventArgs e)
{
if (e == null) {
throw new ArgumentNullException("e");
}
if (ValueChanged != null) {
ValueChanged(this, e);
}
}
public event EventHandler ValueChanged;
public int Value {
get {
return (int)GetValue(ValueProperty);
}
set {
SetValue(ValueProperty, value);
}
}
}
public class SomeBiggerControl : UserControl
{
public SomeBiggerControl()
{
Border parent = new Border();
parent.BorderThickness = new Thickness(2);
parent.Margin = new Thickness(2);
parent.Padding = new Thickness(3);
parent.BorderBrush = Brushes.DarkRed;
SomeControl ctl = new SomeControl();
ctl.SetBinding(SomeControl.ValueProperty,
new Binding("Value") {
Source = this,
Mode = BindingMode.TwoWay
});
parent.Child = ctl;
this.Content = parent;
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value",
typeof(int),
typeof(SomeBiggerControl),
new PropertyMetadata(0));
public int Value {
get {
return (int)GetValue(ValueProperty);
}
set {
SetValue(ValueProperty, value);
}
}
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
}
Window1.xaml
<Window x:Class="CoerceValueTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CoerceValueTest" Height="300" Width="300"
xmlns:local="clr-namespace:CoerceValueTest"
>
<StackPanel>
<local:SomeBiggerControl x:Name="sc"/>
<TextBox Text="{Binding Value, ElementName=sc, Mode=TwoWay}" Name="tb"/>
<Button Content=" "/>
</StackPanel>
</Window>
i.e. two user controls, one nested inside the other, and the outer one of those in a window. The inner user control has a Value dependency property that is bound to a Value dependency property of the outer control. In the window, a TextBox.Text property is bound to the Value property of the outer control.
The inner control has a CoerceValueCallback registered with its Value property whose effect is that this Value property can only be assigned even numbers.
Note that this code is simplified for demonstration purposes. The real version doesn't initialize anything in the constructor; the two controls actually have control templates that do everything that's done in the respective constructors here. That is, in the real code, the outer control doesn't know the inner control.
When writing an even number into the text box and changing the focus (e.g. by focusing the dummy button below the text box), both Value properties get duly updated. When writing an odd number into the text box, however, the Value property of the inner control doesn't change, while the Value property of the outer control, as well as the TextBox.Text property, show the odd number.
My question is: How can I force an update in the text box (and ideally also in the outer control's Value property, while we're at it)?
I have found an SO question on the same problem, but doesn't really provide a solution. It alludes to using a property changed event handler to reset the value, but as far as I can see, that would mean duplicating the evaluation code to the outer control ... which is not really viable, as my actual evaluation code relies on some information basically only known (without much effort) to the inner control.
Moreover, this blogpost suggests invoking UpdateTarget on the binding in TextBox.Text in the CoerceValueCallback, but first, as implied above, my inner control cannot possibly have any knowledge about the text box, and second, I would probably have to call UpdateSource first on the binding of the Value property of the inner control. I don't see where to do that, though, as within the CoerceValue method, the coerced value has not yet been set (so it's too early to update the binding), while in the case that the value is reset by CoerceValue, the property value will just remain what it was, hence a property changed callback will not get invoked (as also implied in this discussion).
One possible workaround I had thought of was replacing the dependency property in SomeControl with a conventional property and an INotifyPropertyChanged implementation (so I can manually trigger the PropertyChanged event even if the value has been coerced). However, this would mean that I cannot declare a binding on that property any more, so it's not a really useful solution.
I have been looking for an answer to this rather nasty bug myself for a while.
One way to do it, without the need to force an UpdateTarget on the bindings is this:
Remove your CoerceValue callback.
Shift the logic of the CoerceValue callback into your ProcessValueChanged callback.
Assign your coerced value to your Value property, when applicable (when the number is odd)
You will end up with the ProcessValueChanged callback being hit twice, but your coerced value will end up being effectively pushed to your binding.
Base on your code, your dependency property declaration would become this:
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value",
typeof(int),
typeof(SomeControl),
new PropertyMetadata(0, ProcessValueChanged, null));
And then, your ProcessValueChanged would become this:
private static void ProcessValueChanged(object source, DependencyPropertyChangedEventArgs e)
{
int baseValue = (int) e.NewValue;
SomeControl someControl = source as SomeControl;
if (baseValue % 2 != 0)
{
someControl.Value = DependencyProperty.UnsetValue;
}
else
{
someControl.ProcessValueChanged(e);
}
}
I slightly modified your logic, to prevent raising the event when the value needs to be coerced. As mentionned before, assigning to someControl.Value the coerced value will cause your ProcessValueChanged to be called twice in a row. Putting the else statement would only raise the events with valid values once.
I hope this helps!

How do I throttle a slider's value change event?

I got a slider that on value change forces a fairly serious computation, so I want to throttle it to fire actual event after for example 50ms pass when user has finished sliding it.
While I learned some various stuff about Rx its unclear how should I approach this using MVVM pattern.
In my current MVVM approach I got slider value bound to my viewModel. I would prefer to add Rx throttle with minimal possible impact on existing code (as a beginning at least).
Ive seen some other threads about MVVM and Rx and I don't think they lead me to some exact direction with my problem. I see various possible approaches and would like not to invent a bycicle.
In this case, you should bind to the PropertyChanged event of your ViewModel, something like:
Observable.FromEvent<PropertyChangedEventArgs>(x => this.PropertyChanged +=x, x => this.PropertyChanged -= x)
.Where(x => x.PropertyName == "SliderName")
.Select(_ => this.SliderName)
.Throttle(TimeSpan.FromMilliseconds(50));
Or, if you were using ReactiveUI, it'd look like this:
this.WhenAnyValue(x => x.SliderName)
.Throttle(TimeSpan.FromMilliseconds(50), RxApp.DeferredScheduler);
Lets just outline the problem. You have a View Model which has some double typed Property. When a value is assigned to this property a fairly expensive calculation takes place. Wouldn't normally be a problem but when the UI binds the value of a Slider to this property the rapid changes generated does create a problem.
First decision to be made is between the view and view-model which is responsible for dealing with this problem. It could be argued both ways the View-Model has "chosen" to make a property assignment an expensice operatione on the other hand the View has "chosen" to assign the property using a Slider.
My choice would be on view side of things because thats a better place to implement this. However rather than fiddle with the View directly I would build a new Control to add the feature. Let's call it the DelaySlider. It will derive from Silder and have two additional dependency properties Delay and DelayedValue. The DelayedValue will match the existing value of Value property but only after Delay milliseconds have elapsed since the last Value changed.
Here is the full code for the control:-
public class DelaySlider : Slider
{
private DispatcherTimer myTimer;
private bool myChanging = false;
#region public double DelayedValue
public double DelayedValue
{
get { return (double)GetValue(DelayedValueProperty); }
set { SetValue(DelayedValueProperty, value); }
}
public static readonly DependencyProperty DelayedValueProperty =
DependencyProperty.Register(
"DelayedValue",
typeof(double),
typeof(DelaySlider),
new PropertyMetadata(0.0, OnDelayedValuePropertyChanged));
private static void OnDelayedValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DelaySlider source = d as DelaySlider;
if (source != null && !source.myChanging)
{
source.Value = (double)e.NewValue;
}
}
#endregion public double DelayedValue
#region public int Delay
public int Delay
{
get { return (int)GetValue(DelayProperty); }
set { SetValue(DelayProperty, value); }
}
public static readonly DependencyProperty DelayProperty =
DependencyProperty.Register(
"Delay",
typeof(int),
typeof(DelaySlider),
new PropertyMetadata(0, OnDelayPropertyChanged));
private static void OnDelayPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DelaySlider source = d as DelaySlider;
if (source != null)
{
source.OnDelayPropertyChanged((int)e.OldValue, (int)e.NewValue);
}
}
private void OnDelayPropertyChanged(int oldValue, int newValue)
{
if (myTimer != null)
{
myTimer.Stop();
myTimer = null;
}
if (newValue > 0)
{
myTimer = new DispatcherTimer();
myTimer.Tick += myTimer_Tick;
myTimer.Interval = TimeSpan.FromMilliseconds(newValue);
}
}
void myTimer_Tick(object sender, EventArgs e)
{
myTimer.Stop();
myChanging = true;
SetValue(DelayedValueProperty, Value);
myChanging = false;
}
#endregion public int Delay
protected override void OnValueChanged(double oldValue, double newValue)
{
base.OnValueChanged(oldValue, newValue);
if (myTimer != null)
{
myTimer.Start();
}
}
}
Now replace your Silder with DelaySlider and bind your View-Model property to the DelayedValue and specify your millisecond delay value in its Delay property.
You now have a useful re-usable control, you haven't messed about with nasty tricks in the View, you have no additional code in the code-behind of the view, the View-Model is unchanged and undisturbed and you haven't had to do include the Rx stuff at all.

Silvelright -set tabindex of UIElements in MVVM

I am trying to set the tab index of two UIElements within a user control. The user control contains a text box and button. I have focus currently being applied to the textbox via an attached property however I would like to have the ability to press the tab key and navigate from the textblock to the button or detect the key press (Enter key) and trigger the command on the button(I know separate question)
The main focus is accomplishing the tab index first.
Thanks for any pointers or suggestions.
UPDATE
I've since tried to employ an attached property to handle the tabbing order
public static DependencyProperty TabIndexProperty = DependencyProperty.RegisterAttached("TabIndex", typeof(int), typeof(AttachedProperties), null);
public static void SetTabIndex(UIElement element, int value)
{
Control c = element as Control;
if (c != null)
{
RoutedEventHandler loadedEventHandler = null;
loadedEventHandler = new RoutedEventHandler(delegate
{
HtmlPage.Plugin.Focus();
c.Loaded -= loadedEventHandler;
c.Focus();
});
c.Loaded += loadedEventHandler;
}
}
However when this I attempt to compile I receive errors that the TabIndex property does not exist for the button control. Any ideas why this is failing?
This is a view specific concern and, as such, even in MVVM should be handled at the ViewLevel. MVVM doesn't stipulate that you remove all code from code behind. It simply means you should have a view specific concern when you do put code there. This is one of those cases, imo.
It is late in the day... I resolved this using an attached property. in the above solution I had copied an earlier DP that I created and did not change the code before I tested.
Below is the working solution
I created a attached properties class and then added the following code:
#region Search Field Focus
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)
{
RoutedEventHandler loadedEventHandler = null;
//set focus on control
loadedEventHandler = new RoutedEventHandler(delegate
{
HtmlPage.Plugin.Focus();
c.Loaded -= loadedEventHandler;
c.Focus();
});
c.Loaded += loadedEventHandler;
}
}
public static bool GetInitialFocus(UIElement element)
{
return false;
}
#endregion
#region Tabbing Order of Elements
public static DependencyProperty TabIndexProperty = DependencyProperty.RegisterAttached("TabIndex", typeof(int), typeof(AttachedProperties), null);
public static void SetTabIndex(UIElement element, int value)
{
element.SetValue(TabIndexProperty, value);
}
public static int GetTabIndex(UIElement element)
{
return (int)element.GetValue(TabIndexProperty);
}
#endregion
The first DP sets the focus of a textblock so that when the user control is loaded you see the cursor placed within the text field.
DP 2 sets the tabbing order. Since the focus is already applied to the current control tabbing falls into place normally. If you did not have focus on the control you would need to set this first.
then finally within the xaml declare your class in the xmlns and add away to the controls.

Resources