The situation is the following:
I have created a custom control which contains among other children a ImageView.
I want to be able to bind a property (IsVisible) of this child view from XAML when using the custom control but am not sure how I can expose this property in the parent custom control.
I want to set something like this (where IsLeftImageVisible should be the exposed child control property):
<controls:StepIndicator IsLeftImageVisible="{Binding IsValid}" />
For now i've done something like this, but I don't really like it:
public static readonly BindableProperty IsLeftButtonVisibleProperty =
BindableProperty.Create<StepIndicator, bool>
(x => x.IsLeftImageVisible, true, propertyChanged: ((
bindable, value, newValue) =>
{
var control = (StepIndicator)bindable;
control.ImageLeft.IsVisible = newValue;
}));
public bool IsLeftImageVisible
{
get { return (bool)GetValue(IsLeftImageVisibleProperty); }
set { SetValue(IsLeftImageVisibleProperty, value); }
}
Is there a way to do this more elgantly?
Alternative way of doing this:
Change LeftImage to private field
Use OnElementPropertyChanged (from renderer) or OnPropertyChanged (from shared class)
From renderer:
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == StepIndicator.IsLeftButtonVisibleProperty.PropertyName)
{
// do something
}
}
From shared class:
protected override void OnPropertyChanged(string propertyName)
{
base.OnPropertyChanged(propertyName);
if (propertyName == StepIndicator.IsLeftButtonVisibleProperty.PropertyName)
{
this.imageLeft.IsVisible = newValue;
}
}
Or subscribe to PropertyChanged event:
PropertyChanged += (sender, e) => {
if (e.PropertyName == StepIndicator.IsLeftButtonVisibleProperty.PropertyName) { // do something }
};
Related
We have setup some Xamarin behavior for not null entry fields etc, this fires when the user makes a change to a field and we then changed the entry border color, red for invalid.
However, we'd also like to reuse this behaviors when a submit button is tapped.
So I need to fire the TextChanged event manually, any ideas how I can do this, now sure if it's possible ?
public class NotEmptyEntryBehaviour : Behavior<Entry>
{
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += OnEntryTextChanged;
base.OnAttachedTo(bindable);
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= OnEntryTextChanged;
base.OnDetachingFrom(bindable);
}
void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
if (args == null)
return;
var oldString = args.OldTextValue;
var newString = args.NewTextValue;
}
}
If you want an alternative you can use one of the pre-built validation behaviors that comes with Xamarin.CommunityToolkit package, like TextValidationBehavior (by specifying a Regexp) or any more specific derived ones (example NumericValidationBehavior) that may fit your needs or even create a custom one by sub-classing ValidationBehavior.
It let you define custom styles for Valid and InValid states, but more important for the question has an async method called ForceValidate().
Also the Flags property could be interesting.
NotEmptyEntryBehaviour seems closer to TextValidationBehavior with MinimumLenght=1
xaml
<Entry Placeholder="Type something..." x:Name="entry">
<Entry.Behaviors>
<xct:TextValidationBehavior Flags="ValidateOnValueChanging"
InvalidStyle="{StaticResource InvalidEntryStyle}"
ValidStyle="{StaticResource ValidEntryStyle}"/>
</Entry.Behaviors>
</Entry>
Code
await (entry.Behaviors[0] as TextValidationBehavior)?.ForceValidate();
Docs
https://learn.microsoft.com/en-us/xamarin/community-toolkit/behaviors/charactersvalidationbehavior
Repo Samples
https://github.com/xamarin/XamarinCommunityToolkit/tree/main/samples/XCT.Sample/Pages/Behaviors
EDIT
If you want to run the validation from the ViewModel you need to bind ForceValidateCommand as explained in this GitHub discussion/question.
We have setup some Xamarin behavior for not null entry fields etc, this fires when the user makes a change to a field and we then changed the entry border color, red for invalid.
You can create custom Entry with behavior to get.
The first I’m going to do is to create a new control that inherits from Entry and will add three properties: IsBorderErrorVisible, BorderErrorColor, ErrorText.
public class ExtendedEntry : Entry
{
public static readonly BindableProperty IsBorderErrorVisibleProperty =
BindableProperty.Create(nameof(IsBorderErrorVisible), typeof(bool), typeof(ExtendedEntry), false, BindingMode.TwoWay);
public bool IsBorderErrorVisible
{
get { return (bool)GetValue(IsBorderErrorVisibleProperty); }
set
{
SetValue(IsBorderErrorVisibleProperty, value);
}
}
public static readonly BindableProperty BorderErrorColorProperty =
BindableProperty.Create(nameof(BorderErrorColor), typeof(Xamarin.Forms.Color), typeof(ExtendedEntry), Xamarin.Forms.Color.Transparent, BindingMode.TwoWay);
public Xamarin.Forms.Color BorderErrorColor
{
get { return (Xamarin.Forms.Color)GetValue(BorderErrorColorProperty); }
set
{
SetValue(BorderErrorColorProperty, value);
}
}
public static readonly BindableProperty ErrorTextProperty =
BindableProperty.Create(nameof(ErrorText), typeof(string), typeof(ExtendedEntry), string.Empty);
public string ErrorText
{
get { return (string)GetValue(ErrorTextProperty); }
set
{
SetValue(ErrorTextProperty, value);
}
}
}
Then creating custom render to android platform.
[assembly: ExportRenderer(typeof(ExtendedEntry), typeof(ExtendedEntryRenderer))]
namespace FormsSample.Droid
{
public class ExtendedEntryRenderer : EntryRenderer
{
public ExtendedEntryRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control == null || e.NewElement == null) return;
UpdateBorders();
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Control == null) return;
if (e.PropertyName == ExtendedEntry.IsBorderErrorVisibleProperty.PropertyName)
UpdateBorders();
}
void UpdateBorders()
{
GradientDrawable shape = new GradientDrawable();
shape.SetShape(ShapeType.Rectangle);
shape.SetCornerRadius(0);
if (((ExtendedEntry)this.Element).IsBorderErrorVisible)
{
shape.SetStroke(3, ((ExtendedEntry)this.Element).BorderErrorColor.ToAndroid());
}
else
{
shape.SetStroke(3, Android.Graphics.Color.LightGray);
this.Control.SetBackground(shape);
}
this.Control.SetBackground(shape);
}
}
}
Finally, Creating an Entry Behavior, handle the error to provide ui feedback to the user when validation occurs
public class EmptyEntryValidatorBehavior : Behavior<ExtendedEntry>
{
ExtendedEntry control;
string _placeHolder;
Xamarin.Forms.Color _placeHolderColor;
protected override void OnAttachedTo(ExtendedEntry bindable)
{
bindable.TextChanged += HandleTextChanged;
bindable.PropertyChanged += OnPropertyChanged;
control = bindable;
_placeHolder = bindable.Placeholder;
_placeHolderColor = bindable.PlaceholderColor;
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
ExtendedEntry customentry = (ExtendedEntry)sender;
if (!string.IsNullOrEmpty(customentry.Text))
{
((ExtendedEntry)sender).IsBorderErrorVisible = false;
}
else
{
((ExtendedEntry)sender).IsBorderErrorVisible = true;
}
}
protected override void OnDetachingFrom(ExtendedEntry bindable)
{
bindable.TextChanged -= HandleTextChanged;
bindable.PropertyChanged -= OnPropertyChanged;
}
void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == ExtendedEntry.IsBorderErrorVisibleProperty.PropertyName && control != null)
{
if (control.IsBorderErrorVisible)
{
control.Placeholder = control.ErrorText;
control.PlaceholderColor = control.BorderErrorColor;
control.Text = string.Empty;
}
else
{
control.Placeholder = _placeHolder;
control.PlaceholderColor = _placeHolderColor;
}
}
}
}
Update:
You can change custom entry's IsBorderErrorVisible in button.click, to call this from submit button.
private void btn1_Clicked(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(entry1.Text))
{
entry1.IsBorderErrorVisible = true;
}
}
<customentry:ExtendedEntry
x:Name="entry1"
BorderErrorColor="Red"
ErrorText="please enter name!">
<customentry:ExtendedEntry.Behaviors>
<behaviors:EmptyEntryValidatorBehavior />
</customentry:ExtendedEntry.Behaviors>
</customentry:ExtendedEntry>
I am creating custom transport controls.
I want to have a Visibility control for a custom Button which I have created. So I have created a Property for it. In that Property, I have used GetTemplateChild("CompactOverlayButton") as Button to get the particular button but it returns null.
Here is my code
public bool IsCompactOverlayButtonVisible
{
get
{
var compactOverlayButton = GetTemplateChild("CompactOverlayButton") as Button;
if (compactOverlayButton.Visibility == Visibility.Visible)
return true;
else
return false;
}
set
{
var compactOverlayButton = GetTemplateChild("CompactOverlayButton") as Button;
if (value)
compactOverlayButton.Visibility = Visibility.Visible;
else
compactOverlayButton.Visibility = Visibility.Collapsed;
}
}
But the same line of code returns proper value in OnApplyTemplate() function.
Here is my code for OnApplyTemplate()
protected override void OnApplyTemplate()
{
var compactOverlayButton = GetTemplateChild("CompactOverlayButton") as Button;
compactOverlayButton.Click += CompactOverlayButton_ClickAsync;
base.OnApplyTemplate();
}
IsCompactOverlayButtonVisible probably gets evaluated for the first time before OnApplyTemplate(), meaning that the first time it gets evaluated, the template hasn't been applied and the button doesn't exist yet. In OnApplyTemplate(), get the button and assign it to a private field.
private Button _compactOverlayButton;
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
_compactOverlayButton = GetTemplateChild("CompactOverlayButton") as Button;
_compactOverlayButton.Click += CompactOverlayButton_ClickAsync;
}
And before you try to touch the button's properties, make sure it's not null.
public bool IsCompactOverlayButtonVisible
{
get
{
return _compactOverlayButton != null
&& _compactOverlayButton.Visibility == Visibility.Visible;
}
set
{
if (_compactOverlayButton != null)
{
compactOverlayButton.Visibility = value
? Visibility.Visible
: Visibility.Collapsed;
}
}
}
If something will set this value before the template is applied, for example if it's a public property of the control that may be set in XAML (which it sure looks like it is), you can't do it this way. You need to make it a regular dependency property, give it a PropertyChanged handler that updates the button's visibility if the button exists, and add a line in OnApplyTemplate() to update the actual button when you get your hands on it. Then it'll be usable as a target of a binding as well.
Update
And here's how you do that. This is the right way.
private Button _compactOverlayButton;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_compactOverlayButton = GetTemplateChild("CompactOverlayButton") as Button;
// Update actual button visibility to match whatever the dependency property value
// is, in case XAML gave us a value for it already.
OnIsCompactOverlayButtonVisibleChanged();
_compactOverlayButton.Click += CompactOverlayButton_Click;
// Secondly, just in case something in the XAML may change the button's visibility,
// put a watch on the property and update our dependency property to match when that
// changes.
var dpd = DependencyPropertyDescriptor.FromProperty(Button.VisibilityProperty, typeof(Button));
dpd.AddValueChanged(_compactOverlayButton, CompactOverlayButton_VisibilityChanged);
}
protected void CompactOverlayButton_VisibilityChanged(object sender, EventArgs args)
{
IsCompactOverlayButtonVisible = _compactOverlayButton.Visibility == Visibility.Visible;
}
private void CompactOverlayButton_Click(object sender, RoutedEventArgs e)
{
// ...whatever
}
#region IsCompactOverlayButtonVisible Property
public bool IsCompactOverlayButtonVisible
{
get { return (bool)GetValue(IsCompactOverlayButtonVisibleProperty); }
set { SetValue(IsCompactOverlayButtonVisibleProperty, value); }
}
public static readonly DependencyProperty IsCompactOverlayButtonVisibleProperty =
DependencyProperty.Register(nameof(IsCompactOverlayButtonVisible), typeof(bool), typeof(CustomMediaTransportControls),
new FrameworkPropertyMetadata(true,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
IsCompactOverlayButtonVisible_PropertyChanged));
protected static void IsCompactOverlayButtonVisible_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// It's a hassle to do stuff in a static method, so my dependency property
// snippet just creates a private instance method and calls it from the
// static handler.
(d as CustomMediaTransportControls).OnIsCompactOverlayButtonVisibleChanged();
}
private void OnIsCompactOverlayButtonVisibleChanged()
{
if (_compactOverlayButton != null)
{
// If the existing value is the same as the new value, this is a no-op
_compactOverlayButton.Visibility =
IsCompactOverlayButtonVisible
? Visibility.Visible
: Visibility.Collapsed;
}
}
#endregion IsCompactOverlayButtonVisible Property
I'm using C#, WPF, ReactiveUI and Prism to create an application with many different views (user controls). On some views there are buttons/menu items that bind to a command in the view model. I would like these buttons to also activate using a key combination such as ctrl+s, etc....
What I've tried
InputBindings but that only works when the view that defines these input bindings has focus.
ApplicationCommands the predefined commands like ApplicationCommands.Close seem useful. I can reference them both in the view and the view model, but I don't know how subscribe to them in my view model. It also seems that I have to 'activate' the command first, or at least change CanExecute since any button bound to such command stays disabled.
What I wish for
Let's say I have a view that represents the top menu bar MenuView with a button myButton and a corresponding view model MenuViewModel with a command myCommand. I would like to bind myButton to myCommand and the keyboard shortcut ctrl+u to myCommand without MenuView knowing about the implementation of its view model. The keyboard shortcut should work as long as the window that contains MenuView has focus.
I don't really care if the keyboard short-cut is either in the view or view model.
You could create an attached Blend behaviour that handles the PreviewKeyDown event of the parent window:
public class KeyboardShortcutBehavior : Behavior<FrameworkElement>
{
private Window _parentWindow;
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(nameof(Command), typeof(ICommand),
typeof(KeyboardShortcutBehavior), new FrameworkPropertyMetadata(null));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public static readonly DependencyProperty ModifierKeyProperty =
DependencyProperty.Register(nameof(ModifierKey), typeof(ModifierKeys),
typeof(KeyboardShortcutBehavior), new FrameworkPropertyMetadata(ModifierKeys.None));
public ModifierKeys ModifierKey
{
get { return (ModifierKeys)GetValue(ModifierKeyProperty); }
set { SetValue(ModifierKeyProperty, value); }
}
public static readonly DependencyProperty KeyProperty =
DependencyProperty.Register(nameof(Key), typeof(Key),
typeof(KeyboardShortcutBehavior), new FrameworkPropertyMetadata(Key.None));
public Key Key
{
get { return (Key)GetValue(KeyProperty); }
set { SetValue(KeyProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += AssociatedObject_Loaded;
AssociatedObject.Unloaded += AssociatedObject_Unloaded;
}
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
_parentWindow = Window.GetWindow(AssociatedObject);
if(_parentWindow != null)
{
_parentWindow.PreviewKeyDown += ParentWindow_PreviewKeyDown;
}
}
private void ParentWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(Command != null && ModifierKey != ModifierKeys.None && Key != Key.None && Keyboard.Modifiers == ModifierKey && e.Key == Key)
Command.Execute(null);
}
private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)
{
if(_parentWindow != null)
{
_parentWindow.PreviewKeyDown -= ParentWindow_PreviewKeyDown;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= AssociatedObject_Loaded;
AssociatedObject.Unloaded -= AssociatedObject_Loaded;
}
}
Sample usage:
<TextBox xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
<i:Interaction.Behaviors>
<local:KeyboardShortcutBehavior ModifierKey="Ctrl" Key="U" Command="{Binding myCommand}" />
</i:Interaction.Behaviors>
</TextBox>
In code behind easy. Create some utility function that eventually lead to an observable of the parent window key events. Note that you will need the ReactiveUI.Events library.
Some utils for handling load and unload of controls.
public static void LoadUnloadHandler
( this FrameworkElement control
, Func<IDisposable> action
)
{
var state = false;
var cleanup = new SerialDisposable();
Observable.Merge
(Observable.Return(control.IsLoaded)
, control.Events().Loaded.Select(x => true)
, control.Events().Unloaded.Select(x => false)
)
.Subscribe(isLoadEvent =>
{
if (!state)
{
// unloaded state
if (isLoadEvent)
{
state = true;
cleanup.Disposable = new CompositeDisposable(action());
}
}
else
{
// loaded state
if (!isLoadEvent)
{
state = false;
cleanup.Disposable = Disposable.Empty;
}
}
});
}
public static IObservable<T> LoadUnloadHandler<T>(this FrameworkElement control, Func<IObservable<T>> generator)
{
Subject<T> subject = new Subject<T>();
control.LoadUnloadHandler(() => generator().Subscribe(v => subject.OnNext(v)));
return subject;
}
and one specifically for handling the window of a loaded control
public static IObservable<T> LoadUnloadHandler<T>
(this FrameworkElement control, Func<Window, IObservable<T>> generator)
{
Subject<T> subject = new Subject<T>();
control.LoadUnloadHandler(() => generator(Window.GetWindow(control)).Subscribe(v => subject.OnNext(v)));
return subject;
}
and finally a key handler for the parent window of any control
public static IObservable<KeyEventArgs> ParentWindowKeyEventObservable(this FrameworkElement control)
=> control.LoadUnloadHandler((Window window) => window.Events().PreviewKeyDown);
now you can do
Button b;
b.ParentWindowKeyEventObservable()
.Subscribe( kEvent => {
myCommand.Execute();
}
It might seem a bit complex but I use the LoadUnloadHandler on most user controls to aquire and dispose resources as the UI lifecycle progresses.
You want to use KeyBindings for this. This allows you to bind keyboard key combos to a command. Read the docs here: https://msdn.microsoft.com/en-us/library/system.windows.input.keybinding(v=vs.110).aspx
Again a have a (probably) simple Problem.
I would like to create a custom UIElement (A Collection of Lines which stay orthogonal).
This UIElement is used as View in my MVVM application.
Here is my code:
class RaOrthogonalLine : Canvas, INotifyPropertyChanged
{
public RaOrthogonalLine()
{
Points.CollectionChanged += Points_CollectionChanged;
}
void Points_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Paint();
}
void Paint()
{
//PaintingStuff! Here I would like to get in!
}
void newLine_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (LineClicked != null)
LineClicked(sender, e);
}
public delegate void LineClickedEventHandler(object sender, MouseButtonEventArgs e);
public event LineClickedEventHandler LineClicked;
public ObservableCollection<RaPoint> Points
{
get
{
return (ObservableCollection<RaPoint>)GetValue(PointsProperty);
}
set
{
SetValue(PointsProperty, value);
RaisePropertyChanged("Points");
}
}
public static readonly DependencyProperty PointsProperty = DependencyProperty.Register("Points", typeof(ObservableCollection<RaPoint>), typeof(RaOrthogonalLine),
new FrameworkPropertyMetadata(new ObservableCollection<RaPoint>(), new PropertyChangedCallback(PointsPropertyChanged))
{
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
}
);
private static void PointsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RaOrthogonalLine thisLine = (RaOrthogonalLine)d;
thisLine.Paint();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
In my XAML I bind a ObservableCollection of my ViewModel to my ObservableCollection in the UIElement(View).
That works fine.
My problem now is that I do not get notified when the Collection changes (Add/Remove/..) - because then i would need to Repaint it.
I tried to get the Points.CollectionChanged event but it does not fire.
Has anyone a idea?
Thank you!
The problem is that you are adding the CollectionChanged Event handler in the constructor of your Control. In the constructor your Paint property is not binded to the right source yet (Indeed it has the PointsProperty's default value, i.e. an empty collection).
You should add and remove the event handler in the PointsPropertyChanged method. Take a look to this sample code:
public class RaOrthogonalLine : Canvas
{
public INotifyCollectionChanged Points
{
get { return (INotifyCollectionChanged)GetValue(PointsProperty); }
set { SetValue(PointsProperty, value); }
}
public static readonly DependencyProperty PointsProperty =
DependencyProperty.Register("Points", typeof(INotifyCollectionChanged), typeof(RaOrthogonalLine),
new FrameworkPropertyMetadata(null, new PropertyChangedCallback(PointsPropertyChanged))
{
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
});
void Points_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Paint();
}
private static void PointsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RaOrthogonalLine raOrthogonalLine = (RaOrthogonalLine)d;
INotifyCollectionChanged newValue = (INotifyCollectionChanged)e.NewValue;
INotifyCollectionChanged oldValue = (INotifyCollectionChanged)e.OldValue;
if (oldValue != null)
{
oldValue.CollectionChanged -= raOrthogonalLine.Points_CollectionChanged;
}
if (newValue != null)
{
newValue.CollectionChanged += raOrthogonalLine.Points_CollectionChanged;
}
raOrthogonalLine.Paint();
}
}
I hope it can help you with your problem.
It might have to do with dependency property but this works just fine for me.
Are you sure you are adding to and removing from the collection (not replacing the collection)?
public class Points
{
void Strings_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Debug.WriteLine("Strings_CollectionChanged");
}
private ObservableCollection<string> strings = new ObservableCollection<string>();
// I think you are better off with just a get
public ObservableCollection<string> Strings { get { return strings; } }
public Points()
{
Strings.CollectionChanged += new NotifyCollectionChangedEventHandler(Strings_CollectionChanged);
Strings.Add("new one");
Strings.Add("new two");
Strings.RemoveAt(0);
}
}
I developed my UI on MVVM pattern and now stuck on getting SelectedItems. Could you please modify my XAML and provide sample how do I get them insde ViewModel class.
<xcdg:DataGridControl Name="ResultGrid" ItemsSource="{Binding Results}" Height="295" HorizontalAlignment="Left" Margin="6,25,0,0" VerticalAlignment="Top" Width="1041" ReadOnly="True">
<xcdg:DataGridControl.View>
<xcdg:TableflowView UseDefaultHeadersFooters="False">
<xcdg:TableflowView.FixedHeaders>
<DataTemplate>
<xcdg:ColumnManagerRow />
</DataTemplate>
</xcdg:TableflowView.FixedHeaders>
</xcdg:TableflowView>
</xcdg:DataGridControl.View>
</xcdg:DataGridControl>
You can use Attached behaviors to get/set SelectedItems to datagrid.
I was facing similar issue in Metro apps, So had to write it myself.
Below is the link
http://www.codeproject.com/Articles/412417/Managing-Multiple-selection-in-View-Model-NET-Metr
Though i had written for metro apps, the same solution can be adapted in WPF/Silverlight.
public class MultiSelectBehavior : Behavior<ListViewBase>
{
#region SelectedItems Attached Property
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register(
"SelectedItems",
typeof(ObservableCollection<object>),
typeof(MultiSelectBehavior),
new PropertyMetadata(new ObservableCollection<object>(), PropertyChangedCallback));
#endregion
#region private
private bool _selectionChangedInProgress; // Flag to avoid infinite loop if same viewmodel is shared by multiple controls
#endregion
public MultiSelectBehavior()
{
SelectedItems = new ObservableCollection<object>();
}
public ObservableCollection<object> SelectedItems
{
get { return (ObservableCollection<object>)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += OnSelectionChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= OnSelectionChanged;
}
private static void PropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
NotifyCollectionChangedEventHandler handler = (s, e) => SelectedItemsChanged(sender, e);
if (args.OldValue is ObservableCollection<object>)
{
(args.OldValue as ObservableCollection<object>).CollectionChanged -= handler;
}
if (args.NewValue is ObservableCollection<object>)
{
(args.NewValue as ObservableCollection<object>).CollectionChanged += handler;
}
}
private static void SelectedItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (sender is MultiSelectBehavior)
{
var listViewBase = (sender as MultiSelectBehavior).AssociatedObject;
var listSelectedItems = listViewBase.SelectedItems;
if (e.OldItems != null)
{
foreach (var item in e.OldItems)
{
if (listSelectedItems.Contains(item))
{
listSelectedItems.Remove(item);
}
}
}
if (e.NewItems != null)
{
foreach (var item in e.NewItems)
{
if (!listSelectedItems.Contains(item))
{
listSelectedItems.Add(item);
}
}
}
}
}
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_selectionChangedInProgress) return;
_selectionChangedInProgress = true;
foreach (var item in e.RemovedItems)
{
if (SelectedItems.Contains(item))
{
SelectedItems.Remove(item);
}
}
foreach (var item in e.AddedItems)
{
if (!SelectedItems.Contains(item))
{
SelectedItems.Add(item);
}
}
_selectionChangedInProgress = false;
}
}
There is probably more to do if you want a multiselection and you want to get those selected items. Do you want to store the selected items and when some action is performed (button clicked or something like that) you want to use those selectedItems and do something with them?
There is a good example on that available here:
Get SelectedItems From DataGrid Using MVVM
It states it is designed for Silverlight, but it will work in WPF with MVVM too.
Perhaps this is a more straightforward approach:
Get Selected items in a WPF datagrid
Creating an attached behavior for wiring up every Read Only Collection or non Dependency property would take a significant amount of work. A simple solution is to pass the reference to the view model using the view.
Private ReadOnly Property ViewModel As MyViewModel
Get
Return DirectCast(DataContext, MyViewModel)
End Get
End Property
Private Sub MyView_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
If ViewModel.SelectedItems Is Nothing Then
ViewModel.SelectedItems = MyDataGrid.SelectedItems
End If
End Sub