How to bind UserControl.IsEnabled to its Command - c#

I have a UserControl declaring a command:
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(MyUserControl));
public ICommand Command
{
get { return (ICommand) GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
The command is assigned by parent UI.
How do I bind the UserControl's IsEnabled to the command's availability?

Try this:
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(UserControl1),
new PropertyMetadata(default(ICommand), OnCommandChanged));
public ICommand Command
{
get { return (ICommand) GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
private static void OnCommandChanged(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var userControl = (UserControl1) dependencyObject;
var command = dependencyPropertyChangedEventArgs.OldValue as ICommand;
if (command != null)
command.CanExecuteChanged -= userControl.CommandOnCanExecuteChanged;
command = dependencyPropertyChangedEventArgs.NewValue as ICommand;
if (command != null)
command.CanExecuteChanged += userControl.CommandOnCanExecuteChanged;
}
private void CommandOnCanExecuteChanged(object sender, EventArgs eventArgs)
{
IsEnabled = ((ICommand) sender).CanExecute(null);
}

You could try this:
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(
"Command", typeof(ICommand), typeof(UserControl1), new PropertyMetadata(null, OnCurrentCommandChanged));
private static void OnCurrentCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
UserControl1 currentUserControl = d as UserControl1;
ICommand newCommand = e.NewValue as ICommand;
if (currentUserControl == null || newCommand == null)
return;
newCommand.CanExecuteChanged += (o, args) => currentUserControl.IsEnabled = newCommand.CanExecute(null);
}
public ICommand Command {
get {
return (ICommand)GetValue(CommandProperty);
}
set {
SetValue(CommandProperty, value);
}
}

Related

Dependency Property command's CanExecute() not updating

I have a user control and within I defined the following property:
public string MyProperty
{
get { return (string)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(string),
typeof(MyUserControlView), new PropertyMetadata(null, MyPropertyChangedCallback));
private static void MyPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (MyUserControl) d;
control.MyProperty = (string)e.NewValue;
}
and the following command:
public ICommand MyCommand
{
get { return (ICommand)GetValue(MyCommandProperty); }
set { SetValue(MyCommandProperty, value); }
}
public static readonly DependencyProperty MyCommandProperty =
DependencyProperty.Register("MyCommand", typeof(ICommand), typeof(MyUserControlView),
new PropertyMetadata(null, MyCommandPropertyChangedCallback));
private static void MyCommandPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (MyUserControlView)d;
control.MyCommand = (DelegateCommand)e.NewValue;
}
void ExecuteMyCommand() {...}
bool CanExecuteMyCommand(){
return !string.IsNullOrWhiteSpace(MyProperty);
}
I Initialize this command with
SetValue(MyCommandProperty, new DelegateCommand(ExecuteMyCommand, CanExecuteMyCommand));
The problem is that the CanExecuteMyCommand() method does not work, because it does not use the current value of MyProperty. Why is this and how can I use my command correctly in a user control?
You have to invoke CanExecuteChanged after changing MyProperty it will call CanExecute.

Attached property cannot be bound

We have a WPF application which has a query count result displayed on the screen. We initially defined the result as a button so that when it was clicked, the application would display a detailed list of the query results. However, for reasons unrelated to this question, we now need this to be a border (basically, just the template for the original button). So far, I have set up my attached property:
public static class AttachedCommandBehavior
{
#region Command
public static DependencyProperty PreviewMouseLeftButtonUpCommandProperty = DependencyProperty.RegisterAttached(
"PreviewMouseLeftButtonUpCommand",
typeof(ICommand),
typeof(AttachedCommandBehavior),
new FrameworkPropertyMetadata(PreviewPreviewMouseLeftButtonUpChanged));
public static void SetPreviewMouseLeftButtonUpChanged(DependencyObject target, ICommand value)
{
target.SetValue(PreviewMouseLeftButtonUpCommandProperty, value);
}
public static ICommand GetPreviewMouseLeftButtonUpChanged(DependencyObject target)
{
return (ICommand)target.GetValue(PreviewMouseLeftButtonUpCommandProperty);
}
private static void PreviewPreviewMouseLeftButtonUpChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is UIElement element)
{
if (e.NewValue != null && e.OldValue == null)
{
element.PreviewMouseLeftButtonUp += element_PreviewMouseLeftButtonUp;
}
else if (e.NewValue == null && e.OldValue != null)
{
element.PreviewMouseLeftButtonUp -= element_PreviewMouseLeftButtonUp;
}
}
}
private static void element_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (sender is UIElement element)
{
if (element.GetValue(PreviewMouseLeftButtonUpCommandProperty) is ICommand command)
command.Execute(CommandParameterProperty);
}
}
#endregion
#region CommandParameter
public static DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached(
"CommandParameter",
typeof(object),
typeof(AttachedCommandBehavior),
new FrameworkPropertyMetadata(CommandParameterChanged));
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 CommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is UIElement element)
{
element.SetValue(CommandParameterProperty, e.NewValue);
}
}
#endregion
}
And then in my XAML, I am trying to bind my command to the attached DependencyProperty:
<Border Background="{Binding BackgroundColor, Converter={StaticResource ColorNameToBrushConverter}}"
Cursor="{x:Static Cursors.Hand}"
local:AttachedCommandBehavior.PreviewMouseLeftButtonUpChanged="{Binding QueryClickedCommand}">
<Grid>...</Grid>
</Border>
However, my little blue squiggly line is telling me "A 'Binding' cannot be used within a 'Border' collection. A 'Binding' can only be set on a DependencyProperty of a DependencyObject." Being the daring programmer that I am, I boldly ignore the little blue squiggly and try to run anyway. At which point I get an exception:
System.Windows.Markup.XamlParseException: 'A 'Binding' cannot be set on the 'SetPreviewMouseLeftButtonUpChanged' property of type 'Viewbox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.'
It turns out this was a naming convention problem. In copying/pasting/renaming/general indecision, I messed up the names of my getter and setter for the command property. Once I changed them all to match the correct pattern, my code runs.
#region Command
public static DependencyProperty PreviewMouseLeftButtonUpCommandProperty = DependencyProperty.RegisterAttached(
"PreviewMouseLeftButtonUpCommand",
typeof(ICommand),
typeof(AttachedCommandBehavior),
new FrameworkPropertyMetadata(PreviewMouseLeftButtonUpChanged));
public static void SetPreviewMouseLeftButtonUpCommand(DependencyObject target, ICommand value)
{
target.SetValue(PreviewMouseLeftButtonUpCommandProperty, value);
}
public static ICommand GetPreviewMouseLeftButtonUpCommand(DependencyObject target)
{
return (ICommand)target.GetValue(PreviewMouseLeftButtonUpCommandProperty);
}
private static void PreviewMouseLeftButtonUpChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is UIElement element)
{
if (e.NewValue != null && e.OldValue == null)
{
element.PreviewMouseLeftButtonUp += element_PreviewMouseLeftButtonUp;
}
else if (e.NewValue == null && e.OldValue != null)
{
element.PreviewMouseLeftButtonUp -= element_PreviewMouseLeftButtonUp;
}
}
}
private static void element_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (sender is UIElement element)
{
if (element.GetValue(PreviewMouseLeftButtonUpCommandProperty) is ICommand command)
command.Execute(CommandParameterProperty);
}
}
#endregion

WPF execute ICommand using attached properties and behaviours

So I'm learning about attached properties and attached behaviours. I have a TextBox and everytime the text is changed, I want to execute some ICommand SomeCommand in my ViewModel which I would bind in the view like this:
<TextBox ... TextUpdateCommand="{Binding Path=SomeCommand}" MonitorTextBoxProperty=true />
MonitorTextBoxProperty is just a property that listens to TextChanged event and then executes ICommand SomeCommand when TextChanged is fired. The ICommand SomeCommand that is executed should come from TextUpdateCommandProperty. How do I link this ICommand SomeCommand to execute it from OnTextBoxTextChanged?
Code:
//Property and behaviour for TextChanged event
public static int GetMonitorTextBoxProperty(DependencyObject obj)
{
return (int)obj.GetValue(MonitorTextBoxProperty);
}
public static void SetMonitorTextBoxProperty(DependencyObject obj, int value)
{
obj.SetValue(MonitorTextBoxProperty, value);
}
public static readonly DependencyProperty MonitorTextBoxProperty =
DependencyProperty.RegisterAttached("MonitorTextBox", typeof(bool), typeof(this), new PropertyMetadata(false, OnMonitorTextBoxChanged));
private static void OnMonitorTextBoxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = (d as TextBox);
if (textBox == null) return;
textBox.TextChanged -= OnTextBoxTextChanged;
if ((bool)e.NewValue)
{
textBox.TextChanged += OnTextBoxTextChanged;
}
}
private static void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
// Execute ICommand by command.Execute()
}
// Property for attaching ICommand that is executed on TextChanged
public static int GetTextUpdateCommandProperty(DependencyObject obj)
{
return (int)obj.GetValue(TextUpdateCommandProperty);
}
public static void SetTextUpdateCommandProperty(DependencyObject obj, int value)
{
obj.SetValue(TextUpdateCommandProperty, value);
}
public static readonly DependencyProperty TextUpdateCommandProperty =
DependencyProperty.RegisterAttached("TextUpdateCommand", typeof(ICommand), typeof(this), new PropertyMetadata(null));
Just get the current value of the TextBox's TextUpdateCommand property using the attached property's get accessor. Try this:
private static void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
var command = GetTextUpdateCommandProperty(textBox);
if (command != null)
command.Execute(null);
}
You should also change the type of the accessors:
public static ICommand GetTextUpdateCommandProperty(DependencyObject obj)
{
return (ICommand)obj.GetValue(TextUpdateCommandProperty);
}
public static void SetTextUpdateCommandProperty(DependencyObject obj, ICommand value)
{
obj.SetValue(TextUpdateCommandProperty, value);
}
And typeof(this) should the typeof(TheClassName) in the call to DependencyProperty.RegisterAttached.

Usercontrol's PropertyChangedCallback not fired

I'm having really hard time trying to make listbox multiselection bindable, basically the same as this article : http://blogs.microsoft.co.il/miziel/2014/05/02/wpf-binding-listbox-selecteditems-attached-property-vs-style/
This is my class for the listbox :
public partial class ListBoxMultipleSelection : UserControl
{
public ListBoxMultipleSelection()
{
InitializeComponent();
this.DataContext = this;
}
public static readonly DependencyProperty ItemSourceProperty =
DependencyProperty.Register("ItemSource", typeof(ObservableCollection<string>), typeof(ListBoxMultipleSelection), new PropertyMetadata(new ObservableCollection<string>()));
public ObservableCollection<string> ItemSource
{
get { return (ObservableCollection<string>)this.GetValue(ItemSourceProperty); }
set { this.SetValue(ItemSourceProperty, value); }
}
private static ListBox list;
private static bool _isRegisteredSelectionChanged = false;
///
/// SelectedItems Attached Dependency Property
///
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.RegisterAttached("SelectedItems", typeof(IList),
typeof(ListBoxMultipleSelection),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(OnSelectedItemsChanged)));
public static IList GetSelectedItems(DependencyObject d)
{
return (IList)d.GetValue(SelectedItemsProperty);
}
public static void SetSelectedItems(DependencyObject d, IList value)
{
d.SetValue(SelectedItemsProperty, value);
}
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!_isRegisteredSelectionChanged)
{
var listBox = (ListBox)d;
list = listBox;
listBox.SelectionChanged += listBox_SelectionChanged;
_isRegisteredSelectionChanged = true;
}
}
private static void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
IEnumerable listBoxSelectedItems = list.SelectedItems;
IList ModelSelectedItems = GetSelectedItems(list);
ModelSelectedItems.Clear();
if (list.SelectedItems != null)
{
foreach (var item in list.SelectedItems)
ModelSelectedItems.Add(item);
}
SetSelectedItems(list, ModelSelectedItems);
}
}
And the XAML for the usercontrol/listbox :
<Grid>
<ListBox SelectionMode="Multiple"
local:ListBoxMultipleSelection.SelectedItems="{Binding DataContext.SelectedItems}"
ItemsSource="{Binding DataContext.ItemSource, ElementName=MultiListBox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
The problem is "listBox_SelectionChanged" is never fired and so nothing is updated correctly. Any idea ?
Thank you

collection dependency properties

I have a custom control that has a DependencyProperty of type ObservableCollection that is bound to an observableCollection:
<MyControl MyCollectionProperty = {Binding MyObservableCollection} ...
Problem is adding to MyObservableCollection does not update MyCollectionProperty.
I need to completly replace the MyObservableCollection to make it work e.g.
MyObservableCollection = null;
MyObservableCollection = new ObservableCollection(){...}
Is there a better way to deal with this?
EDIT:
public ObservableCollection<string> Columns
{
get { return (ObservableCollection<string>)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("Columns", typeof(ObservableCollection<string>), typeof(MyControl),
new PropertyMetadata(new ObservableCollection<string>(), OnChanged));
In addition to what grantz has answered, I would suggest to declare the property with type IEnumerable<string> and check at runtime if the collection object implements the INotifyCollectionChanged interface. This provides greater flexibility as to which concrete collection implementation may be used as property value. A user may then decide to have their own specialized implementation of an observable collection.
Note also that in the ColumnsPropertyChanged callback the CollectionChanged event handler is attached to the new collection, but also removed from the old one.
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register(
"Columns", typeof(IEnumerable<string>), typeof(MyControl),
new PropertyMetadata(null, ColumnsPropertyChanged));
public IEnumerable<string> Columns
{
get { return (IEnumerable<string>)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
private static void ColumnsPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var control= (MyControl)obj;
var oldCollection = e.OldValue as INotifyCollectionChanged;
var newCollection = e.NewValue as INotifyCollectionChanged;
if (oldCollection != null)
{
oldCollection.CollectionChanged -= control.ColumnsCollectionChanged;
}
if (newCollection != null)
{
newCollection.CollectionChanged += control.ColumnsCollectionChanged;
}
control.UpdateColumns();
}
private void ColumnsCollectionChanged(
object sender, NotifyCollectionChangedEventArgs e)
{
// optionally take e.Action into account
UpdateColumns();
}
private void UpdateColumns()
{
...
}
Below is a working example that may help.
In this example, the method OnChanged is called immediately, when the Add button is clicked "Changed" is written to the console.
The Control
public class MyControl : Control
{
public ObservableCollection<string> ExtraColumns
{
get { return (ObservableCollection<string>)GetValue(ExtraColumnsProperty); }
set { SetValue(ExtraColumnsProperty, value); }
}
public static readonly DependencyProperty ExtraColumnsProperty =
DependencyProperty.Register("ExtraColumns", typeof(ObservableCollection<string>), typeof(MyControl),
new PropertyMetadata(new ObservableCollection<string>(), OnChanged));
static void OnChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
(sender as MyControl).OnChanged();
}
void OnChanged()
{
if ( ExtraColumns != null )
ExtraColumns.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ExtraColumns_CollectionChanged);
}
void ExtraColumns_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
Console.WriteLine("Changed");
}
}
The Window
<Window x:Class="WpfApplication18.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication18"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:MyControl ExtraColumns="{Binding Extras}"/>
<Button Click="Button_Click">Add</Button>
</StackPanel>
</Window>
Window Code Behind
public partial class MainWindow : Window
{
private ObservableCollection<string> _extras = new ObservableCollection<string>( );
public ObservableCollection<string> Extras
{
get { return _extras; }
set
{
if (value != _extras)
{
_extras = value;
}
}
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Extras.Add("Additional");
}
}

Categories

Resources