Binding to a Dependency Property of UserControl - wpf

I have a WPF user control that has a DependencyProperty called IsMultiSelect. I want to show hide a Button in the UserControl xaml.
<Button Visibility="{Binding IsMultiSelect, Converter=....}" />
This user control has a ViewModel assigned to the DataContext.
The above syntax gives me a binding error due to the property not existing in the view model.
How can I fix this error?

You can target the UserControl in different ways in the binding.
One solution would be to find it by setting a RelativeSource like this:
<Button Visibility="{Binding IsMultiSelect,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
Converter=....}" />

Instead of binding to the property from xaml, the property changed handler for the dependency property should change the button's visibility.
public static readonly DependencyProperty IsMultiSelectProperty = DependencyProperty.Register("IsMultiSelect", typeof(bool), typeof(MyUserControl), new PropertyMetadata(false, OnIsMultiSelectPropertyChanged));
private static void OnIsMultiSelectPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
(sender as MyUserControl).OnIsMultiSelectPropertyChanged(e);
}
private void OnIsMultiSelectPropertyChanged(DependencyPropertyChangedEventArgs e)
{
MyButton.Visibility = (bool)e.NewValue ? Visibility.Visible : Visibility.Collapsed;
}
public bool IsMultiSelect
{
get { return (bool)GetValue(IsMultiSelectProperty); }
set { SetValue(IsMultiSelectProperty, value); }
}
And you can put the converter logic inside OnIsMultiSelectPropertyChanged as well.

Related

Binding 'SelectedItems' dependency property to ViewModel property does not work

I have a multiselect Combobox usercontrol and a dependency property 'SelectedItems'.
I m trying to use the usercontrol and bind the 'SelectedItems' to another property called 'SelectedResultItems' in my ViewModel. But I dont get any values to SelectedResultItems. Please help
Here is what i tried.
My main xaml:
<DataTemplate x:Key="TypeATemplate">
<control:MultiSelectComboBox Width="315" ItemsSource="{Binding
ResultvalueList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedItems="{Binding
SelectedResultItems,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
My Combobox usercontrol code behind:
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems",
typeof(ObservableCollection<string>), typeof(MultiSelectComboBox), new
FrameworkPropertyMetadata(null,new
PropertyChangedCallback(MultiSelectComboBox.OnSelectedItemsChanged)));
public ObservableCollection<string> SelectedItems
{
get { return
(ObservableCollection<string>)GetValue(SelectedItemsProperty); }
set
{
SetValue(SelectedItemsProperty, value);
}
}
I am setting the 'SelectedItems' on click of the checkbox.
My mainviewmodel:
public ObservableCollection<string> SelectedResultItems
{
get => _selectedResultItems;
set
{
_selectedResultItems = value;
NotifyPropertyChanged(nameof(SelectedResultItems));
}
}
If this is the same as for ListView(never used MultiSelectCombobox), you cannot bind to SelectedItems because it is a read-only property.
What I did to solve that is add the event SelectionChanged to ListView(or MultiSelectCombobox for you).
Then event would be :
private void YourComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
contexte.ResultItems = YourComboBox.SelectedItems.Cast<YourItem>().ToList();
}
Maybe there is a different way to do it, but until now that's the easiest way I found.

Binding to dependency property in usercontrol

I have a UserControl that contains a ListBox and I want to track the SelectedItems of that listbox.
The UserControl has a DP "SelectedItemsList" that is defined like this
public static DependencyProperty SelectedItemsListProperty = DependencyProperty.Register(
"SelectedItemsList",
typeof (IList),
typeof (MyListControl),
new FrameworkPropertyMetadata(null,
OnSelectedItemsChanged));
In the listbox' Item "SelectionChanged" event, I want to save the selected items to the DP. This is triggered whenever I change the selection in the listbox.
private void OnItemSelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedItemsList = this.myListBox.SelectedItems;
}
In my view that contains the "MyListControl" I create a binding to my viewmodel that want to use the selected items.
<controls:MyListControl
Source="{Binding SomeItemsList, UpdateSourceTrigger=PropertyChanged}"
SelectedItemsList="{Binding SelectedItems, UpdateSourceTrigger=PropertyChanged}"/>
My problem is, that the DP SelectedItemsList never gets updated. The PropertyChangeCallback "OnSelectedItemsChanged" of the DP is only triggered when I initially load the lists content. The value of the SelectedItemsList is always null.
I am aware that this question is similar to Dependency property callback does not work, but the answers posted there do not solve my problem.
What am I missing here?
Thanks,
Edit (2015-09-10):
Thank you all for your comments. I found a solution that fits my needs:
First of all I created a custom listbox control that provided the list of selected items in a dependency property (very similar to Select multiple items from a DataGrid in an MVVM WPF project).
public class CustomListBox : ListBox
{
public static readonly DependencyProperty SelectedItemsListProperty =
DependencyProperty.Register("SelectedItemsList",
typeof (IList),
typeof (CustomListBox),
new PropertyMetadata(null));
public CustomListBox()
{
SelectionChanged += OnSelectionChanged;
}
public IList SelectedItemsList
{
get { return (IList)GetValue(SelectedItemsListProperty); }
set { SetValue(SelectedItemsListProperty, value); }
}
void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.SelectedItemsList= new ArrayList(this.SelectedItems);
}
}
I am not happy yet with the "new ArrayList"-part, but if in my viewmodel's property setter I want to check for equality, SelectedItemsList can not be a reference of SelectedItems. The previous and the new value would always be the same.
Then I reduced the item selection parts of my UserControl "MyListControl" simply to the dependency property itself:
public static DependencyProperty SelectedItemsProperty = DependencyProperty.Register(
"SelectedItems",
typeof (IList),
typeof (MyListControl),
new FrameworkPropertyMetadata(null));
public IList SelectedItems
{
get
{
return (IList)GetValue(SelectedItemsProperty);
}
set
{
SetValue(SelectedItemsProperty, value);
}
}
and modified the xaml of the MyListControl:
<controls:CustomListBox
SelectionMode="Extended"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type controls:MyListControl}},
Path=Source, UpdateSourceTrigger=PropertyChanged}"
SelectedItemsList="{Binding RelativeSource={RelativeSource AncestorType={x:Type controls:MyListControl}},
Path=SelectedItems, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
>
The property in my ViewModel looks like
public IList SelectedObjects
{
get { return _selectedObjects; }
set { if (this._selectedObjects != value)
{
this._selectedObjects = value;
OnPropertyChanged(SelectedObjectsProperty);
}
}
}
It was important that the type of this property is IList, otherwise the value in the setter would always be null.
And in the view's xaml
<controls:MyListControl
Source="{Binding CurrentImageList, UpdateSourceTrigger=PropertyChanged}"
SelectedItems="{Binding SelectedObjects, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
/>
I just had the same problem today, unfortunately, when you are assigning to SelectedItemsList a value, WPF seems to unbind it. To fix it, I update the value in the binded item. I know that it is not the best solution in the world but for me it works.
In this case the code would looked like this:
private void OnItemSelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.SetPropertyValue(
this.GetBindingExpression(SelectedItemsListProperty),
this.myListBox.SelectedItems);
}
private void SetPropertyValue(BindingExpression bindingExpression, object value)
{
string path = bindingExpression.ParentBinding.Path.Path;
var properties = new Queue<string>(
path.Split(
new[]
{
'.'
}).ToList());
this.SetPropertyValue(bindingExpression.DataItem, bindingExpression.DataItem.GetType(), properties, value);
}
private void SetPropertyValue(object destination, Type type, Queue<string> properties, object value)
{
PropertyInfo property = type.GetProperty(properties.Dequeue());
if (property != null && destination != null)
{
if (properties.Count > 0)
{
this.SetPropertyValue(property.GetValue(destination), property.PropertyType, properties, value);
}
else
{
property.SetValue(destination, value);
}
}
}
You need to bind your Listbox' SelectedItems to the DP SelectedItemsList to propagate the user selection to the DP. The binding you already have will then pass the changes on to the viewmodel, but I think you will need a binding mode 'twoway' instead of UpdateSourceTrigger.
And don't use the PropertyChangeCallback in your DP: Changing the SelectedItemsList if the SelectedItemsListProperty has changed makes no sense. (Usually the former is a wrapper property of the latter.)

WPF dependency property Databinding

I have very basic question regarding dependency property and data-binding. I have created a simple class name TDTVm its my ViewModel class. It has one bool dependency property named IsShaftMovingUp and its initial value is 'False' I have bound this value to one text box on UI. Now I want to show real-time value of 'IsShaftMovingUp' on the screen.
Below is my VM.
public class TDTVm : DependencyObject
{
public static DependencyProperty ShaftMovingUpProperty =
DependencyProperty.Register(
"ShaftMovingUp",
typeof(bool),
typeof(TDTVm),
new PropertyMetadata(false, ShaftMovingUpChanged));
private static void ShaftMovingUpChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine("ok");
}
public bool IsShaftMovingUp
{
get => (bool)GetValue(TDTVm.ShaftMovingUpProperty);
set => SetValue(TDTVm.ShaftMovingUpProperty, value);
}
}
Below is my xamal code.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Button Content="Button" Click="Button_Click"/>
<TextBox Text="{Binding IsShaftMovingUp,
UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
and below is my code behind:
public partial class MainWindow : Window
{
TDTVm datacontext = new TDTVm();
public MainWindow()
{
InitializeComponent();
this.DataContext = datacontext;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
///Even after this line 'true' value is not getting updated on UI.
datacontext.IsShaftMovingUp = true;
}
}
When I click on button I am setting value of 'IsShaftMovingUp' to true. But still on UI its not getting updated. ( I have achieved this using INotifyPropertyChanged but want to try same with dependency property to understand exact difference between the two )
Thanks
To fix your problem, you need to change this code
DependencyProperty.Register("ShaftMovingUp",
into
DependencyProperty.Register("IsShaftMovingUp",
Check this post, if you want to know the difference between INotifyPropertyChanged and Dependency Property.

Silverlight TextBox VisibilityChanged event

I'm working on a Windows Phone app using Silverlight C# and XAML. My page contains a ListBox which renders a list of databound objects that the user can manipulate, i.e. add/rename/delete.
I've got it working that the add/rename of items is done in-place, i.e. by swapping a TextBlock for a TextBox depending on the state of the object (bool IsEditable property) and making use of a parameterized VisibilityConverter to manage the opposite Visibility states.
<UserControl.Resources>
<local:VisibilityConverter x:Key="VisibilityConverter" True="Visible" False="Collapsed"/>
<local:VisibilityConverter x:Key="InvertedVisibility" True="Collapsed" False="Visible"/>
</UserControl.Resources>
...
<TextBlock Text="{Binding Name}" Visibility="{Binding IsEditable, Converter={StaticResource InvertedVisibility}}" />
<TextBox Text="{Binding Name}" Visibility="{Binding IsEditable, Converter={StaticResource VisibilityConverter}}"/>
The thing is that I also want the TextBox to automatically grab focus when it becomes visible, so that the on-screen keyboard pops up without the user having to tap the TextBox.
Since there's no VisibilityChanged event on a regular TextBox, I subclassed TextBox to TextBox2 and added my own:
public class TextBox2 : TextBox
{
public TextBox2()
{
DefaultStyleKey = typeof(TextBox);
}
public static readonly DependencyProperty VisibilityChangedProperty = DependencyProperty.Register(
"VisibilityChanged",
typeof(string),
typeof(TextBox2),
new PropertyMetadata("Set the VisibilityChanged event handler"));
public event VisibilityChangedEventHandler VisibilityChanged;
public delegate void VisibilityChangedEventHandler(object sender, EventArgs e);
public new Visibility Visibility
{
get
{
return base.Visibility;
}
set
{
if (base.Visibility != value)
{
base.Visibility = value;
VisibilityChanged(this, new EventArgs());
}
}
}
}
Now my XAML looks like this:
<TextBlock Text="{Binding Name}" Visibility="{Binding IsEditable, Converter={StaticResource InvertedVisibility}}"/>
<local:TextBox2 Text="{Binding Name}" Visibility="{Binding IsEditable, Converter={StaticResource VisibilityConverter}}" VisibilityChanged="ListEdit_VisibilityChanged"/>
And the event handler like this:
void ListEdit_VisibilityChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Visibility == System.Windows.Visibility.Collapsed)
return;
textBox.Focus();
}
The TextBox2 renders properly and behaves just like a TextBox at runtime, but my VisibilityChanged event handler is not firing when the databinding flips the value of IsEditable.
IsEditable defines the Visibility and the TextBox2 does become visible correctly, so the databinding is working.
I can cause the event to fire programmatically by getting hold of the TextBox2 instance and setting the Visibility of that in code. That also works.
But this databinding scenario being responsible for setting the Visibility seems not to work.
Any ideas why not?
Here are 2 solutions that I use.
Solution 1 needs no sub class, but solution 2 is more reusable.
1. You can subscribe to the Loaded event of the TextBox, and force a focus, like so:
void TextBox_Loaded_Focus(object sender, System.Windows.RoutedEventArgs e) {
ForceFocusControl((Control)sender);
}
void ForceFocusControl(Control control) {
control.Focus();
if (FocusManager.GetFocusedElement() != control) {
Dispatcher.BeginInvoke(() => ForceFocusControl(control));
}
}
This solution goes into a recursive loop though, you might want to add some checks to make it safer.
2. Keep your subclass TextBox2, and rather create a private MyVisibility dependency property that you bind to the Visibility property of the base class, but also specify a DependencyProperty_Changed handler, like so:
/// <summary>
/// <see cref="TextBox2"/> will focus itself when it becomes visible.
/// </summary>
public sealed class TextBox2 : TextBox {
public TextBox2() {
SetBinding(TextBox2.MyVisibilityProperty, new Binding("Visibility") { Source = this });
}
static readonly DependencyProperty MyVisibilityProperty = DependencyProperty.Register(
/* name = */ "MyVisibilityProperty",
/* property type = */ typeof(Visibility),
/* owner type = */ typeof(TextBox2),
/* meta = */ new PropertyMetadata(MyVisibilityProperty_Changed));
static void MyVisibilityProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
TextBox2 TextBox2 = (TextBox2)d;
if (TextBox2.Visibility == Visibility.Visible) {
TextBox2.Focus();
}
}
}
This is how my TextBox2 class looks now:
public class TextBox2 : TextBox
{
public event VisibilityChangedEventHandler VisibilityChanged;
public delegate void VisibilityChangedEventHandler(object sender, EventArgs e);
public static readonly DependencyProperty VisibilityChangedProperty = DependencyProperty.Register(
"VisibilityChanged", typeof(VisibilityChangedEventHandler), typeof(TextBox2), null);
static readonly DependencyProperty MirrorVisibilityProperty = DependencyProperty.Register(
"MirrorVisibility", typeof(Visibility), typeof(TextBox2), new PropertyMetadata(MirrorVisibilityChanged));
public TextBox2()
{
SetBinding(TextBox2.MirrorVisibilityProperty, new Binding("Visibility") { Source = this });
}
static void MirrorVisibilityChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((TextBox2)obj).VisibilityChanged(obj, null); // raise event
}
}

Checkbox at MainWindow that sets values to controls located on underlaying UserControls

In MainWindow class I have checkbox that controls property used by many objects like grids, listviews, etc in UserControls
<CheckBox Content="Show objects ID" Name="showID" IsChecked="False" />
than there is property defined,
public Visibility ShowObjectIDasVisibility
{
get { return showID.IsChecked.Equals(true) ? Visibility.Visible : Visibility.Collapsed; }
}
I have some more like this to return boolean, width depending on what should be used on target control.
I managed to bind controls located in UserControl objects to use this property like this:
<TextBlock Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=ShowObjectIDasVisibility}" />
But it works only ones, while creating this TextBlock, than I can toggle checkbox as many times I like, and the TextBlock will stay visible or not depending on first value.
How should I do this properly? Thanks.
Instead of INotifyPropertyChanged interface you can use DependencyProperty:
public Visibility ShowObjectIDasVisibility
{
get { return (Visibility)GetValue(ShowObjectIDasVisibilityProperty); }
set { SetValue(ShowObjectIDasVisibilityProperty, value); }
}
public static readonly DependencyProperty ShowObjectIDasVisibilityProperty =
DependencyProperty.Register("ShowObjectIDasVisibility", typeof(Visibility), typeof(MainWindow), new PropertyMetadata(Visibility.Collapsed));
Now, to show/hide your TextBlock you need to change ShowObjectIDasVisibility value.
For example, you can do it by adding to checkbox Click="OnShowID_Click and in code behind
private void OnShowID_Click(object sender, RoutedEventArgs e)
{
ShowObjectIDasVisibility = ShowObjectIDasVisibility == System.Windows.Visibility.Visible ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
}
if your binding is correct. you just need to make sure that your code class is implementing INotifyPropertyChanged interface in class binded to view and you are raising RaisePropertyChanged event in every checkbox state change. For more details look at example here.

Resources