Issues with MouseDoubleClick command on TreeViewItem using AttachedProperties - wpf

I am trying to attach a Command and CommandParameter property to a TreeViewItem so I can route a mouse double click event to a Command in the ViewModel. It appears that the double click event is never even fired.
MouseDoubleClick:
namespace VisualInspectionConsole.Commands
{
public class MouseDoubleClick
{
public static DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(MouseDoubleClick),
new UIPropertyMetadata(CommandChanged));
public static DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached(
"CommandParameter",
typeof(object),
typeof(MouseDoubleClick),
new UIPropertyMetadata(null));
public static void SetCommand(DependencyObject target, ICommand value)
{
target.SetValue(CommandProperty, value);
}
public static void SetCommandParameter(DependencyObject target, object value)
{
target.SetValue(CommandParameterProperty, value);
}
public static object GetCommandParameter(DependencyObject target)
{
return target.GetValue(CommandParameterProperty);
}
private static void CommandChanged(
DependencyObject target, DependencyPropertyChangedEventArgs e)
{
Control control = target as Control;
if (control != null)
{
if ((e.NewValue != null) && (e.OldValue == null))
{
control.MouseDoubleClick += OnMouseDoubleClick;
}
else if ((e.NewValue == null) && (e.OldValue != null))
{
control.MouseDoubleClick -= OnMouseDoubleClick;
}
}
}
private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
{
Control control = sender as Control;
((ICommand) control.GetValue(CommandProperty)).Execute(
control.GetValue(CommandParameterProperty));
}
}
}
Tree view code in MainWindow.xaml:
<Window
...................
xmlns:commands ="clr-namespace:VisualInspectionConsole.Commands"
...................
<TreeView
Width="275"
Name="tvwWaferList"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ItemsSource="{Binding TreeviewViewModel.WaferList}"
SelectedValuePath="Wafer"
Background="{StaticResource accentBrushOne}"
Foreground="Black"
FontFamily="SegoeUI"
FontWeight="Bold"
Margin="1"
BorderBrush="{StaticResource primaryBrush}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="Foreground" Value="{StaticResource primaryBrush}"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter
Property="commands:MouseDoubleClick.Command"
Value="{Binding SelectWaferCommand}"/>
<Setter
Property="commands:MouseDoubleClick.CommandParameter"
Value="{Binding}"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Wafers}">
<TextBlock
Text="{Binding}"
Foreground="Black"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Can anyone tell me why the mouse double click is not working?
Edit: Getting this error in the output window:
System.Windows.Data Error: 40 : BindingExpression path error: 'SelectWaferCommand' property not found on 'object' ''WaferHierarchyModel' (HashCode=4494425)'. BindingExpression:Path=SelectWaferCommand; DataItem='WaferHierarchyModel' (HashCode=4494425); target element is 'TreeViewItem' (Name=''); target property is 'Command' (type 'ICommand')

So after some reading I was able to get this work correctly. I just had to change the commands:MouseDoubleClick.Commands value
from
{Binding SelectWaferCommand}"
to
{Binding DataContext.TreeviewViewModel.SelectWaferCommand,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeView}}}"
because the WaferHierarchyModel objects do not have a SelectWaferCommand, the TreeviewViewModel does. This basically tells it to execute the SelectWaferCommand found in the nearest TreeView ancestors DataContext.TreeviewViewModel object.

Related

How to access Canvas instance when it is in ItemsPanel?

I have changed my view from simple Canvas to ItemsControl that uses Canvas, because I want to bind Canvas children to my ViewModel.
It was like this:
<Canvas x:Name="worksheetCanvas">
<local:BlockControl DataContext="{Binding x}"/>
<local:BlockControl DataContext="{Binding y}"/>
<local:BlockControl DataContext="{Binding z}"/>
</Canvas>
I "moved" step forward to MVVM and now I have this:
<ItemsControl x:Name="itemsControl" ItemsSource="{Binding Blocks}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas x:Name="worksheetCanvas">
<!-- Here I have some attached properties defined -->
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Top" Value="{Binding BlockTop}"/>
<Setter Property="Canvas.Left" Value="{Binding BlockLeft}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:BlockControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I have to access Canvas from code behind (I don't want pure MVVM, there will be some code behind). I have set x:Name property for Canvas inside ItemsPanelTemplate, but it doesn't work:
Error CS0103 The name 'worksheetCanvas' does not exist in the current context
I guess this is because Canvas is created after compilation and cannot be accessed like this.
What is the best (efficient) way to get my Canvas reference in this scenario?
You could create a derived ItemsControl (as a WPF custom control) with a Canvas as items host and a property that makes the Canvas accessible.
public class CanvasItemsControl : ItemsControl
{
static CanvasItemsControl()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(CanvasItemsControl),
new FrameworkPropertyMetadata(typeof(CanvasItemsControl)));
}
public Canvas Canvas { get; private set; }
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
Canvas = Template.FindName("Canvas", this) as Canvas;
}
}
Accessing the Canvas like this works with a default Style in Themes/Generic.xaml as shown below. It does not set the ItemsPanel property, but instead directly puts the hosting Canvas into the ControlTemplate of the ItemsControl.
<Style TargetType="{x:Type local:CanvasItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ItemsControl">
<Canvas x:Name="Canvas" IsItemsHost="True"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Your XAML would then look like this:
<local:CanvasItemsControl x:Name="itemsControl" ItemsSource="{Binding Blocks}">
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Top" Value="{Binding BlockTop}"/>
<Setter Property="Canvas.Left" Value="{Binding BlockLeft}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:BlockControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</local:CanvasItemsControl>
As soon as the Template has been applied, you are able to access the Canvas property, e.g. in a Loaded event handler of the Window:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
itemsControl.Canvas.Background = Brushes.AliceBlue;
}
You could use the VisualTreeHelper class to find the Canvas in the visual tree once the ItemsControl has been loaded, e.g.:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Canvas worksheetCanvas = FindVisualChild<Canvas>(itemsControl);
//...
}
private static childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
{
return (childItem)child;
}
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
}
You can create UserControl wrapper. And then access to canvas by Content property
<ItemsPanelTemplate>
<local:MyCanvasWrapper>
<Canvas x:Name="worksheetCanvas">
<!-- Here I have some attached properties defined -->
</Canvas>
</local:MyCanvasWrapper>
</ItemsPanelTemplate>
Code behind
public partial class MyCanvasWrapper : UserControl // Or ContentControl
{
public MyCanvasWrapper()
{
InitializeComponent();
Loaded += (s, e) => {
var canvas = Content as Canvas;
}
}
}

Changing dependency property on behavior

I Have a Behavior that I created a dependency property on it, this behavior is used in an item template of a ListBox.
What I need to do is change the value in the dependency property when the ListBoxItem is selected.
I tried to give the Behavior a name in the Xaml but the trigger didn't recognize it (compilation error).
I tried creating a 0 sized grid, changing the color of the background of that grid in the trigger and binding the dependency property to the background of that grid, it took the first value but didn't update when the trigger changed the background.
Behavior class:
public class DragToCenter : Behavior<FrameworkElement>
{
public static readonly DependencyProperty CenteredTextColorProperty = DependencyProperty.Register(
"CenteredTextColor",
typeof(Color),
typeof(DragToCenter),
new UIPropertyMetadata(Brushes.Black.Color, CenteredTextColorPropertyChanged));
private static void CenteredTextColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DragToCenter lBase = d as DragToCenter;
if (lBase != null)
{
d.SetValue(CenteredTextColorProperty, e.NewValue);
lBase.DrowImage();
}
}
public Color CenteredTextColor
{
get
{
return (Color)GetValue(CenteredTextColorProperty);
}
set
{
SetValue(CenteredTextColorProperty, value);
}
}
protected override void OnAttached()
{
// Do something
}
private void DrowImage()
{
// Do something that changes the view so it will be visible if this is triggered
}
XAML:
<ListBox ItemsSource="{Binding DisplayValues}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid x:Name="CenterText" Height="0" Width="0" Background="Gray"/>
<Border>
<i:Interaction.Behaviors>
<b:DragToCenter CenteredTextColor="{Binding ElementName=CenterText, Path=Background.Color}"/>
</i:Interaction.Behaviors>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True">
<Setter TargetName="CenterText" Property="Background" Value="White"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Edit:
The idea is to change the behavior functionality (a small change) when the row is selected in the ListBox

When PropertyChanged called event PropertyChanged=null

I have a class derived from INotifyPropertyChanged to track property changes. This properties are bound to a TreeView and are needed to perform searching in TreeViewItems. When in properties setters this.OnPropertyChanged("IsExpanded") is called for some reason this.PropertyChanged == null when "IsExpanded" bubbled to the root element of the TreeView. Why is it null here and not null on deeper TreeView elements? What can I to solve this issue?
My code cs:
public class TreeViewItemViewModel:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
....................
bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
if (value != _isExpanded)
{
_isExpanded = value;
this.OnPropertyChanged("IsExpanded");
}
//Expand all till the root
if (_isExpanded && _parent != null)
_parent._isExpanded = true;
//Lazy load children, if nessesary
if (this.HasDummyChild)
{
this.Children.Remove(DummyChild);
this.LoadChildren();
}
}
}
bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if (value != _isSelected)
{
_isSelected = value;
this.OnPropertyChanged("IsSelected");
}
}
}
.............................
}
My code XAML:
<TreeView ItemsSource="{Binding Areas}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontWeight" Value="Normal" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.Resources>
<HierarchicalDataTemplate
DataType="{x:Type vAreas:AreaViewModel}"
ItemsSource="{Binding Children}"
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
The problem was that I never subscribe for my event PropertyChanged.
As soon as I subscribe for it it start to work fine
this.PropertyChanged += AreaViewModel_PropertyChanged;
void AreaViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsExpanded")
{
//Expand all till the root
if (this.IsExpanded && this.Parent != null)
this.Parent.IsExpanded = true;
//Lazy load children, if nessesary
if (this.HasDummyChild)
{
this.Children.Remove(DummyChild);
this.LoadChildren();
}
}
}
I struggled with this one for a while. In the end it turned out that my collection feeding the treeview was an ObservableCollection property, but was actually a list.
As soon as I turned it into an ObservableCollection everything started working.

Using DataGridComboBoxColumn as autocompletecombobox in a DataGrid

I want to use the DataGridComboBoxColumn as a autocomplete combobox.
I've got it partially working. When the Row is in EditMode I can type text in the ComboBox, also in ViewMode the control returns the text. Only how to get the Label (in template) to EditMode by mouse doubleclick?
Up front, I don't want to use the DataGridTemplateColumn control because it just doesn't handle keyboard and mouse entry like the DataGridComboBoxColumn does (tabs, arrows, edit/view mode/ double click etc..).
It looks like:
I fixed it adding a behavior to the TextBox to get a link to the parent DataGrid then setting the Row into Edit Mode by calling BeginEdit().
The solution I used:
View
<Window x:Class="WpfApplication1.MainWindow"
xmlns:local="clr-namespace:WpfApplication1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}" />
</Window.Resources>
<Grid>
<DataGrid ItemsSource="{Binding Model.Things}" Name="MyGrid" ClipboardCopyMode="IncludeHeader">
<DataGrid.Resources>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Object" MinWidth="140" TextBinding="{Binding ObjectText}" ItemsSource="{Binding Source={StaticResource proxy}, Path=Data.Model.ObjectList}" >
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="IsEditable" Value="True"/>
<Setter Property="Text" Value="{Binding ObjectText}"/>
<Setter Property="IsSynchronizedWithCurrentItem" Value="True" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<TextBox IsReadOnly="True" Text="{Binding Path=DataContext.ObjectText, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}}">
<TextBox.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="local:CellSelectedBehavior.IsCellRowSelected" Value="true"></Setter>
</Style>
</TextBox.Resources>
</TextBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Model
public class Model : BaseModel
{
//List of objects for combobox
private List<string> _objectList;
public List<string> ObjectList { get { return _objectList; } set { _objectList = value; } }
//Rows in datagrid
private List<Thing> _things;
public List<Thing> Things
{
get { return _things; }
set { _things = value; OnPropertyChanged("Things"); }
}
}
public class Thing : BaseModel
{
//Text in combobox
private string _objectText;
public string ObjectText
{
get { return _objectText; }
set { _objectText = value; OnPropertyChanged("ObjectText"); }
}
}
ViewModel
public class ViewModel
{
public Model Model { get; set; }
public ViewModel()
{
Model = new WpfApplication1.Model();
Model.ObjectList = new List<string>();
Model.ObjectList.Add("Aaaaa");
Model.ObjectList.Add("Bbbbb");
Model.ObjectList.Add("Ccccc");
Model.Things = new List<Thing>();
Model.Things.Add(new Thing() { ObjectText = "Aaaaa" });
}
}
Behavior
public class CellSelectedBehavior
{
public static bool GetIsCellRowSelected(DependencyObject obj) { return (bool)obj.GetValue(IsCellRowSelectedProperty); }
public static void SetIsCellRowSelected(DependencyObject obj, bool value) { obj.SetValue(IsCellRowSelectedProperty, value); }
public static readonly DependencyProperty IsCellRowSelectedProperty = DependencyProperty.RegisterAttached("IsCellRowSelected",
typeof(bool), typeof(CellSelectedBehavior), new UIPropertyMetadata(false, OnIsCellRowSelected));
static void OnIsCellRowSelected(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
TextBox item = depObj as TextBox;
if (item == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool)e.NewValue)
item.MouseDoubleClick += SelectRow;
else
item.MouseDoubleClick -= SelectRow;
}
static void SelectRow(object sender, EventArgs e)
{
TextBox box = sender as TextBox;
var grid = box.FindAncestor<DataGrid>();
grid.BeginEdit();
}
}
Helper (to find DataGrid)
public static class Helper
{
public static T FindAncestor<T>(this DependencyObject current) where T : DependencyObject
{
current = VisualTreeHelper.GetParent(current);
while (current != null)
{
if (current is T)
{
return (T)current;
}
current = VisualTreeHelper.GetParent(current);
};
return null;
}
}

Wpf disable repeatbuttons when scrolled to top/bottom

I'm making a touchscreen interface that uses a listbox.
I have a button above and below the listbox for page up/down.
I'm trying to get it to where when scrolled all the way up the pageup button gets disabled.
and when scrolled all the way down the pagedown button gets disabled too.
Here's the code in my Styles.xaml for the Listbox
<Style x:Key="{x:Type ListBox}" TargetType="{x:Type ListBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate x:Key="{x:Type ListBox}" TargetType="{x:Type ListBox}">
<DockPanel>
<RepeatButton x:Name="LineUpButton" DockPanel.Dock="Top"
HorizontalAlignment="Stretch"
Height="50"
Content="/\"
Command="{x:Static ScrollBar.PageUpCommand}"
CommandTarget="{Binding ElementName=scrollviewer}" />
<RepeatButton x:Name="LineDownButton" DockPanel.Dock="Bottom"
HorizontalAlignment="Stretch"
Height="50"
Content="\/"
Command="{x:Static ScrollBar.PageDownCommand}"
CommandTarget="{Binding ElementName=scrollviewer}" />
<Border BorderThickness="1" BorderBrush="Gray" Background="White">
<ScrollViewer x:Name="scrollviewer">
<ItemsPresenter/>
</ScrollViewer>
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Hidden"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Hidden"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
</Style>
And here's where I instantiate the listbox
<ListBox SelectedItem="{Binding SelectedCan}" ItemsSource="{Binding Path=SelectedKioskCashCans}">
<ListBox.ItemTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding image}" MaxWidth="75" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
I searched all around yesterday with no luck.
I'm hoping to be able to do it all in xaml.
I'm using images for the buttons but took them out for readability above,
they really look like...
<RepeatButton x:Name="LineUpButton" DockPanel.Dock="Top" HorizontalAlignment="Stretch"
Height="50"
Command="{x:Static ScrollBar.PageUpCommand}"
CommandTarget="{Binding ElementName=scrollviewer}">
<RepeatButton.Template>
<ControlTemplate TargetType="{x:Type RepeatButton}">
<Grid>
<Image Name="Normal" Source="/Images/up.png"/>
<Image Name="Pressed" Source="/Images/up.png" Visibility="Hidden"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
<Setter TargetName="Pressed" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</RepeatButton.Template>
</RepeatButton>
Just use CanExecute method of the PageUpCommand for that. Return false if where are no pages left and the button will become disabled automatically.
EDIT:
I have created a simple attached behavior that can be used to fix this problem. Just set the following attached property on the ScrollViewer:
<ScrollViewer x:Name="scrollviewer"
z:ScrollBarCommandsCanExecuteFixBehavior.IsEnabled="True">
<ItemsPresenter/>
</ScrollViewer>
And here is the source code of the behavior:
public static class ScrollBarCommandsCanExecuteFixBehavior
{
#region Nested Types
public class CommandCanExecuteMonitor<T> where T : UIElement
{
protected T Target { get; private set; }
protected CommandCanExecuteMonitor(T target, RoutedCommand command)
{
Target = target;
var binding = new CommandBinding(command);
binding.CanExecute += OnCanExecute;
target.CommandBindings.Add(binding);
}
protected virtual void OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
}
}
public class PageUpCanExecuteMonitor : CommandCanExecuteMonitor<ScrollViewer>
{
public PageUpCanExecuteMonitor(ScrollViewer scrollViewer)
: base(scrollViewer, ScrollBar.PageUpCommand)
{
}
protected override void OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled)
{
return;
}
if (Equals(Target.VerticalOffset, 0.0))
{
e.CanExecute = false;
e.Handled = true;
}
}
}
public class PageDownCanExecuteMonitor : CommandCanExecuteMonitor<ScrollViewer>
{
public PageDownCanExecuteMonitor(ScrollViewer scrollViewer)
: base(scrollViewer, ScrollBar.PageDownCommand)
{
}
protected override void OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled)
{
return;
}
if (Equals(Target.VerticalOffset, Target.ScrollableHeight))
{
e.CanExecute = false;
e.Handled = true;
}
}
}
#endregion
#region IsEnabled Attached Property
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool) obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached("IsEnabled", typeof (bool), typeof (ScrollBarCommandsCanExecuteFixBehavior), new PropertyMetadata(false, OnIsEnabledChanged));
private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((bool) e.NewValue)
{
var scrollViewer = d as ScrollViewer;
if (scrollViewer != null)
{
OnAttached(scrollViewer);
}
else
{
throw new NotSupportedException("This behavior only supports ScrollViewer instances.");
}
}
}
private static void OnAttached(ScrollViewer target)
{
SetPageUpCanExecuteMonitor(target, new PageUpCanExecuteMonitor(target));
SetPageDownCanExecuteMonitor(target, new PageDownCanExecuteMonitor(target));
}
#endregion
#region PageUpCanExecuteMonitor Attached Property
private static void SetPageUpCanExecuteMonitor(DependencyObject obj, PageUpCanExecuteMonitor value)
{
obj.SetValue(PageUpCanExecuteMonitorProperty, value);
}
private static readonly DependencyProperty PageUpCanExecuteMonitorProperty =
DependencyProperty.RegisterAttached("PageUpCanExecuteMonitor", typeof (PageUpCanExecuteMonitor), typeof (ScrollBarCommandsCanExecuteFixBehavior), new PropertyMetadata(null));
#endregion
#region PageDownCanExecuteMonitor Attached Property
private static void SetPageDownCanExecuteMonitor(DependencyObject obj, PageDownCanExecuteMonitor value)
{
obj.SetValue(PageDownCanExecuteMonitorProperty, value);
}
private static readonly DependencyProperty PageDownCanExecuteMonitorProperty =
DependencyProperty.RegisterAttached("PageDownCanExecuteMonitor", typeof (PageDownCanExecuteMonitor), typeof (ScrollBarCommandsCanExecuteFixBehavior), new PropertyMetadata(null));
#endregion
}
The basic idea is that we add a CommandBinding to the ScrollViewer for each of the commands and subscribe to the CanExecute event on those bindings. In the event handler we check the current position of the scroll and set the e.CanExecute property accordingly.

Resources