WPF Cannot Bind Dependancy Property From Custom UserControl - wpf

I have MultiSelectComboBox UserControl inside my Custom UserControl.
I'd like to bind the SelectedItems Dependency Property (from the MSCB above) which is type of Dictionary to any of My ViewModel Property...
*MSBC means --> MultiSelectComboBox UserControl !!!!!
Code-Behind of the MSCB:
Define DP:
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(Dictionary<string, object>), typeof (MultiSelectComboBox), new FrameworkPropertyMetadata(null,
new PropertyChangedCallback(MultiSelectComboBox.OnSelectedItemsChanged)));
Define SelectedItems Property in MSCB:
public Dictionary<string, object> SelectedItems
{
get { return (Dictionary<string, object>)GetValue(SelectedItemsProperty); }
set
{
SetValue(SelectedItemsProperty, value);
}
}
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MultiSelectComboBox ctrl = (MultiSelectComboBox)d;
ctrl.SelectNodes();
ctrl.SetText();
}
Xaml of My Custum UserControl:
Define the MSCB in the Xaml:
<MultiSelectComboBox:MultiSelectComboBox x:Name="WorkDay"
SelectedItems="{Binding SelectedItemsInViewModel}"
ItemsSource="{Binding WorkDays,Converter={StaticResource DataConverter}}"/>
In My ViewModel class:
private Dictionary<string, object> si= new Dictionary<string, object>();
public Dictionary<string, object> SelectedItemsInViewModel
{
get { return si; }
set
{
si = value;
OnPropertyChanged("SelectedItemsInViewModel");
}
}
It looks like the OnEventChanged (of the DProperty inside MSBC) is fired only for the first initialization and then stop firing.
I don't get any changes in my ViewModel property.
I've set the data context to point to my ViewModel class and other bindings inside this CustomControl are working fine (like TextBoxes).

Looks like your code is incomplete.
If the idea is to implement a Multi selection combo box, then you will need to more than just defining a SelectedItems property - you will need populate it when a item is selected/un-selected.
About,
I don't get any changes in my ViewModel property
Are you updating (SetValue) this property from View also? Or is it other way round?

The solution worked for me is to use value converter interface, also you were right about using SetValue(), I've used it but the SelectedItems dictionary didn't set when I change the SelectedItems Dictionary because the DP point to referential object and when the list changing nothing happen unless you change the DP address each time, so I've added this line: SelectedItems = SelectedItems;
private void SetSelectedItems()
{
if (SelectedItems == null)
SelectedItems = new Dictionary<string, object>();
SelectedItems.Clear();
foreach (Node node in _nodeList)
{
if (node.IsSelected && node.Title != "ALL")
{
if (this.ItemsSource.Count > 0)
SelectedItems.Add(node.Title, this.ItemsSource[node.Title]);
}
}
SelectedItems = SelectedItems; //ADDED THIS LINE SOLEVED The DP not changed Problem
}
after that I've used IValueConverter Interface in my ViewModel To handle Dictionary and convert it to what I've needed....
Thanks for helping me out to get the solution , guess I saved few more hours...

Related

How do I pass changes from source in a TwoWay binding?

I have created a custom TextBox control (but not derived from TextBox) that contains a Dependency Property "Text".
I have added an instance of this and bound it to a property on my view model using a TwoWay binding.
From within my custom TextBox control, how do I update the Text property in such a way that the change is propagated to the property on the view model?
If I set the "Text" property on my custom control, that replaces the binding leaving the property on the view model as null.
I would have thought this would be simple but I can't see how to do it (the standard TextBox control must do it!)
Cheers
Edit:
Custom Control:
public class SampleCustomControl : CustomControl
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(SampleCustomControl), new PropertyMetadata(null));
public void Update()
{
// This replaces my binding, I want it to pass the new value
// through to the "SomeProperty" two way binding.
Text = "some value";
}
}
Usage:
<Controls:SampleCustomControl Text="{Binding SomeProperty, Mode=TwoWay}" />
You need to add a Property Changed callback in the metadata of your dependency property.
This callback will be fired when the Text property changes (from either side). You can use the value passed in from this to update your custom UI that you've built to display the text.
Update:
Responding to your comment about what this is about. Since your example code is too vague to test, here is what I used to test your problem.
public class TestControl : ContentControl
{
private TextBlock _tb;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_tb = new TextBlock();
_tb.Text = Text;
this.Content = _tb;
_tb.MouseLeftButtonDown += new MouseButtonEventHandler(_tb_MouseLeftButtonDown);
}
void _tb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Update();
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(TestControl), new PropertyMetadata(string.Empty, OnTextChanged));
public void Update()
{
// This replaces my binding, I want it to pass the new value
// through to the "SomeProperty" two way binding.
Text = "some value";
}
public static void OnTextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((TestControl)sender).UpdateText((string)e.NewValue);
}
protected void UpdateText(string text)
{
if (_tb != null) _tb.Text = text;
}
}
I then bound the Text property on my control to the view model using a two way binding. When I click the text in the view both the view and the viewmodel get updated with the new text "some value". If I update the value in the viewmodel (and raise the property changed event) the value gets updated in the view and the control so the binding is still valid.
There must be some other missing pieces in your example.
As long as your binding property is set to TwoWay and you have exposed the getter and the setter, than the text you enter in the TextBox is sent to the ViewModel. I believe the actual send occurs when you lose focus of that control however, i believe.

How to create silverlight 4 usercontrol with dependency property that can accept any type

I am looking for a way to create an UserControl in silverlight 4 and expose a dependency property, which can accept any type. What I mean by that is, for example, if you look at standard silverlight control like AutoCompleteBox, it is capable of handling any type of collections. So you can bind AutoCompleteBox with IEnumerable<Human> or IENumerable<Animal> etc. And when any item is selected AutoCompleteBox returns the selected value either Human instance or Animal instance via SelectedItem dependency property.
I want to achieve similar flexibility with my usercontrol. I wouild like to expose 2 dependency properties SuggestedItems and SelectedItem. Which ever collection is set to SuggestedItems via consumers of this usercontrol thru Binding, lets take as an example IEnumerable<Car>, the I want SelectedItem property to send instance of Car type back to consumer thru Binding. If I used IEnumerable<Boat>, then I need Boat to be returned with SelectedItem.
I was trying to achieve it by using below example using MVVM, but its not working. I am looking for some clues as to how it should be designed, Am I even on a correct path or I have to completely alter my design?
I created an UserControl called VehicleSelectorUserControl which has its own dedicated ViewModel called VehicleSelectorViewModel with two proerties SuggestedItems, SelectedItem.
And usercontrol has corresponding Dependency properties in its codebehind to expose them to consumers of usercontrol. UserControl XAML has a ListBox which is bound to SuggestedItems property of VehicleSelectorViewModel. When user makes a selection, VehicleSelectorViewModel SelectedItem is set, which them invokes a delegate called ItemSelected to notify VehicleSelectorUserControl codebehind, which then sets the SelectedItem Dependency property to make it available to consumer.
Below is code from the VehicleSelectorUserControl.xaml.cs code behind.
private VehicleSelectorViewModel _TheViewModel;
public UserNameControl()
{
InitializeComponent();
_TheViewModel = Resources["TheViewModel"] as VehicleSelectorViewModel;
_TheViewModel.ItemSelected = OnItemSelected;
}
public IEnumerable<object> SuggestedItems
{
get { return (IEnumerable<object>)GetValue(SuggestedItemsProperty); }
set { SetValue(SuggestedItemsProperty, value); }
}
public static readonly DependencyProperty SuggestedItemsProperty =
DependencyProperty.Register("SuggestedItems", typeof(IEnumerable<object>), typeof(VehicleSelectorControl), new PropertyMetadata(OnSuggestedItemsSet));
private static void OnSuggestedItemsSet(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
_TheViewModel.SuggestedItems = e.NewValue;
}
public object SelectedItem
{
get { return (String) GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(object), typeof(VehicleSelectorControl), null);
private void OnItemSelected()
{
SelectedItem = _TheViewModel.SelectedItem;
}
Its ViewModel VehicleSelectorViewModel code
public Action ItemSelected { get; set; }
private dynamic _SelectedItem;
public dynamic SelectedItem
{
get { return _SelectedItem; }
set
{
if (value != _SelectedItem)
{
_SelectedItem = value;
NotifyPropertyChanged("SelectedItem");
if(ItemSelected != null) ItemSelected.Invoke();
}
}
}
private dynamic _SuggestedItems;
public dynamic SuggestedItems
{
get { return _SuggestedItems; }
set
{
if (value != _SuggestedItems)
{
_SuggestedItems = value;
NotifyPropertyChanged("SuggestedItems");
}
}
}
The XAML of consumer will look like (Consumer has its own ViewModel, which responsible for supplying SuggestedCars [IEnumerable<Car>], SuggestedBoats [IEnumerable<Boat>].
<my:VehicleSelectorControl x:Name="MyCarSelectorControl"
SuggestedItems="{Binding SuggestedCars, Mode=TwoWay}"
SelectedItem="{Binding UserSelectedCar, Mode=TwoWay}" />
<my:VehicleSelectorControl x:Name="MyBoatSelectorControl"
SuggestedItems="{Binding SuggestedBoats, Mode=TwoWay}"
SelectedItem="{Binding UserSelectedBoat, Mode=TwoWay}" />

User Control with custom ItemsSource dependency property

I've got a UserControl with an ItemsSource property. As the base UserControl class does not implement ItemsSource, I had to create my own dependency property like this:
#region ItemsSource Dependency Property
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(MonthViewControl),
new PropertyMetadata(OnItemsSourceChanged));
static void OnItemsSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
(obj as MonthViewControl).OnItemsSourceChanged(e);
}
private void OnItemsSourceChanged(DependencyPropertyChangedEventArgs e)
{
RefreshLayout();
}
public IEnumerable ItemsSource
{
get
{
return (base.GetValue(ItemsSourceProperty) as IEnumerable);
}
set
{
base.SetValue(ItemsSourceProperty, value);
}
}
#endregion
Now in my ViewModel I have an Events property which is an ICollectionView of EventItem items like so:
private ObservableCollection<Controls.EventCalendar.EventItem> eventItems;
private CollectionViewSource events;
public System.ComponentModel.ICollectionView Events
{
get
{
if (events == null)
{
events = new CollectionViewSource();
events.Source = eventItems;
}
return events.View;
}
}
The issue I'm facing is that in my View, when I bind to the Events property, and I add an Item to eventItems, the UserControl won't fire the ItemsSourceChanged event and hence not update the UI.
For the sake of testing I added a simple listbox to the view which also binds to the Events property. That works like a charm. Updates to eventItems observableCollection are reflected in the ListBox.
I'm figuring it has something to do with my ItemsSource dependency property. Maybe I would need to use a Custom Control which inherits form ItemsControl instead of a UserControl?
To help you understand my problem: I'm trying to create a calendar like control which shows events/agenda entries (similar to Google Calendar). It works like a charm. The UI is updated when the control is resized. The only thing that's left is the automagical update once the ItemsSource changes.
Hope someone can help.
EDIT: The moment I posted I realized that the event can't be fired as the ItemsSource property does not change. It is the underlying collection that changes. However, I'm not how to handle that. What do I need to implement to make this work. Just a hint would be enough. I don't need every implementation details.
Opening the PresentationFramework.dll within Reflector and looking at System.Windows.Controls.ItemsControl showed the following:
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);
}
control.OnItemsSourceChanged(oldValue, newValue);
}
Not knowing what RefreshLayout does my hunch is that it has something to do with the way the ObservableCollection<T> is being wrapped as the above code is oblivious to what the concrete collection type is and it would therefore be handled by the type being wrapped; in this case an ObservableCollection<T> Try modifying your property as seen below to return the default view and adjust your ItemsSource property to be more akin to the above code from the framework and work backwards from there.
private ObservableCollection<Controls.EventCalendar.EventItem> eventItems;
private ICollectionview eventsView;
public System.ComponentModel.ICollectionView Events
{
get
{
if (eventsView == null)
eventsView = CollectionViewSource.GetDefaultView(eventItems);
return eventsView;
}
}

WPF MVVM Bind list on custom control to ViewModel

Is it possible to bind data in the "wrong" direction? I want a value in a custom control to be bound to my ViewModel. I've tried binding with mode "OneWayToSource" but I can't get it to work.
Scenario (simplified):
I have a custom control (MyCustomControl) that has a dependency property that is a list of strings:
public class MyCustomControl : Control
{
static MyCustomControl()
{
//Make sure the template in Themes/Generic.xaml is used.
DefaultStyleKeyProperty.OverrideMetadata(typeof (MyCustomControl), new FrameworkPropertyMetadata(typeof (MyCustomControl)));
//Create/Register the dependency properties.
CheckedItemsProperty = DependencyProperty.Register("MyStringList", typeof (List<string>), typeof (MyCustomControl), new FrameworkPropertyMetadata(new List<string>()));
}
public List<string> MyStringList
{
get
{
return (List<string>)GetValue(MyCustomControl.MyStringListProperty);
}
set
{
var oldValue = (List<string>)GetValue(MyCustomControl.MyStringListProperty);
var newValue = value;
SetValue(MyCustomControl.MyStringListProperty, newValue);
OnPropertyChanged(new DependencyPropertyChangedEventArgs(MyCustomControl.MyStringListProperty, oldValue, newValue));
}
}
public static readonly DependencyProperty MyStringListProperty;
}
The control also contains code to manipulate this list.
I use this custom control in a UserControl that has a ViewModel. The ViewModel has a property that is also a list of strings:
public List<string> MyStringsInTheViewModel
{
get
{
return _myStringsInTheViewModel;
}
set
{
if (value != _myStringsInTheViewModel)
{
_myStringsInTheViewModel = value;
OnPropertyChanged("MyStringsInTheViewModel");
}
}
}
private List<string> _myStringsInTheViewModel;
Now I want to bind the list in my custom control (MyStringList) to the list in my ViewModel (MyStringsInTheViewModel) so that when the list is changed in the custom control it is also changed in the ViewModel. I've tried this but can't get it to work...
<myns:MyCustomControl MyStringList="{Binding Path=MyStringsInTheViewModel, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}">
How can I make such a binding?
Use ObservableCollection<T> instead of List<T>. It implements INotifyCollectionChanged Interface.

CollectionType Dependency Property

Based on this tutorial:
http://www.dotnetfunda.com/articles/article961-wpf-tutorial--dependency-property-.aspx
I've created my usercontrol like this:
usercontrol xaml:
<UserControl x:Class="PLVS.Modules.Partner.Views.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tp="http://thirdparty.com/controls"
x:Name="UC">
<tp:ContainerControl x:Name="tpControl">
<tp:ContainerControl.Items>
<tp:SomeItem SomeProperty="SomeValue">
<TextBlock Text="SomeText"/>
</tp:SomeItem>
</ig:TabItemEx>
</tp:ContainerControl.Items>
</tp:ContainerControl>
</UserControl>
usercontrol code-behind:
public partial class TestControl : UserControl
{
public TestControl()
{
InitializeComponent();
SetValue(TestItemsPropertyKey, new ObservableCollection<ThirdPartyClass>());
}
public ObservableCollection<ThirdPartyClass> TestItems
{
get
{
return (ObservableCollection<ThirdPartyClass>)GetValue(TabItemsProperty);
}
}
public static readonly DependencyPropertyKey TestItemsPropertyKey =
DependencyProperty.RegisterReadOnly("TestItems", typeof(ObservableCollection<ThirdPartyClass>), typeof(TestControl), new UIPropertyMetadata(new ObservableCollection<ThirdPartyClass>(), TestItemsChangedCallback));
public static readonly DependencyProperty TestItemsProperty = TestItemsPropertyKey.DependencyProperty;
private static void TestItemsChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
TestControl ib = obj as TestControl;
var newNvalue = e.NewValue; // Why is e.NewValue null???
}
}
I want to later use the usercontrol like this:
<localControl:TestControl x:Name="testControl">
<localControl:TestControl.TabItems>
<tp:SomeItem SomeProperty="SomeValue">
<TextBlock Text="SomeText2"/>
</tp:SomeItem>
<tp:SomeItem SomeProperty="SomeValue">
<TextBlock Text="SomeText3"/>
</tp:SomeItem>
</tp:ContainerControl.Items>
</localControl:TestControl>
In the above code i've added a callback function in my usercontrol so that i can add the new items to the container control "tpControl" declared in the xaml. However when the callback function is triggered the new value is empty. And the question here is why?
Are you actually seeing e.NewValue as null or as an empty collection?
In your code you're setting a default value for the property to an ObservableCollection instance (which you generally shouldn't do for reference types - just use null) and then assigning another instance of the ObservableCollection in your control's instance constructor, which is triggering the Changed callback. At this point you are now assigning this new empty collection, which is what you should be seeing for e.NewValue.
If you want to access the items declared in XAML you need to wait until after they have been added to the collection. Adding the items will not cause the change handler for the property to fire because you're not assigning a new collection to the DP. You can either use a handler for a different event that occurs later (like Loaded)
Loaded += (sender, e) => { DoSomething(TestItems) };
or attach a CollectionChanged handler to the e.NewValue instance which will be called each time an item is added, removed, moved, etc.
var newValue = e.NewValue as ObservableCollection<ThirdPartyClass>;
newValue.CollectionChanged += (sender, args) => { DoSomething(TestItems); };

Resources