I am working on WPF project. I create a usercontrol containing a combobox; which represent boolean value(True or false). And I register a DependencyProperty Value for my usercontrol.
Whenever combobox selection was changed, I will update the Value property and also when Value property is update I will update combobox.
But I found the problem when I use my usercontrol in MVVM. I bind the Value property with my IsEnable property in my viewModel. I set binding mode as TwoWay binding. But when I changed selection in comboBox, IsEnable property is never set.
My usercontrol:
public bool Value
{
get { return (bool)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(bool),
typeof(BooleanComboBox),
new UIPropertyMetadata(true, OnValuePropertyChanged));
private void Cmb_Selection_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox cmb = sender as ComboBox;
object selectedValue = cmb.SelectedValue;
if (selectedValue == null)
{
this.Value = false;
}
else
{
if (selectedValue.GetType() == typeof(bool))
{
this.Value = (bool)selectedValue;
}
else
{
this.Value = false;
}
}
if (this.OnValueChange != null)
this.OnValueChange(this, this.Value);
}
private static void OnValuePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
BooleanComboBox self = sender as BooleanComboBox;
self.Cmb_Selection.SelectedValue = (bool)args.NewValue;
}
In window, where I place my usercontrol (I already set usercontrol's datacontext to my viewModel):
<tibsExtControl:BooleanComboBox Grid.Row="4"
Grid.Column="1"
VerticalAlignment="Center"
Value="{Binding Path=NewTemporaryZone.IsEnable,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
x:Name="Cmb_AllowNonLBILogon"/>
In my model class I declare an IsEnable property:
private bool _isEnable;
public bool IsEnable
{
get { return _isEnable; }
set
{
_isEnable= value;
OnPropertyChanged("IsEnable");
}
}
What's going on with my usercontrol. I miss something ? Please help me. T.T
Please check whether you have any binding error in the output window of VS.
Try refreshing your binding in Cmb_Selection_SelectionChanged. Something like:
BindingExpression b = cmb.GetBindingExpression(MyNamespace.ValueProperty);
b.UpdateSource();
I've had the same problem; with boolean dependency properties! Try switching the bool to a INullable<bool> (bool?) and apply the appropriate type conversions. This worked for me. Don't know if this is a bug or if value types are handled somewhat different compared to reference types when creating dependency properties? Maybe someone else could verify that.
Related
I have a custom control with a ViewModel. In this control I make programatically binding from the properties of the control to the ViewModel.
When I use the control and I make a binding to the property the value's aren't updated. I have the this for the bindings
In the customControl ViewModel
private string _InitValue;
public string InitValue
{
get { return _InitValue; }
set { _InitValue = value; NotifyPropertyChanged();}
}
In the customControl I set the binding
initValueBinding = new Binding();
initValueBinding.Source = LocalDataContext;
initValueBinding.Path = new PropertyPath("InitValue");
initValueBinding.Mode = BindingMode.OneWayToSource;
initValueBinding.BindsDirectlyToSource = true;
initValueBinding.UpdateSourceTrigger = UpdateSourceTrigger.Default;
BindingOperations.SetBinding(this, PlusMinControl.InitValueProperty, initValueBinding);
The InitValueProperty is a dependency property.
public static DependencyProperty InitValueProperty = DependencyProperty.Register(nameof(InitValue), typeof(string), typeof(PlusMinControl), new PropertyMetadata( new PropertyChangedCallback(test)) );
private static void test(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
;
}
public string InitValue
{
get { return ((string)(base.GetValue(PlusMinControl.InitValueProperty))); }
set { base.SetValue(PlusMinControl.InitValueProperty, value); }
}
For the implementation of the customControl
<plm:PlusMinControl InitValue="{Binding InitVal}" />
In the code behind I set the datacontext and I've InitVal defined as a normal property.
When I debug the code I can trace the changes till the PropertyChangedCallback but the property in the viewmodel isn't updated.
Can anyone tell me what I do wrong? And how I should fix this.
Thank you!
you have inverted and mixed same init :
this makes the binding property=viewmodel
<plm:PlusMinControl InitValue="{Binding InitVal}" />
and this too
"initValueBinding = new Binding();....."
this must be enough, remove the binding code
<plm:PlusMinControl InitialValue ="{Binding InitValue}" />
change the property to InitialValue in the control
change BindingMode.OneWayToSource to BindingMode.TwoWay
I have a UserControl named MultiChartControl, which has a dependency property named MultiChartInputDetails.
public ChartsData MultiChartInputDetails
{
get { return (ChartsData)GetValue(MultiChartInputDetailsProperty); }
set { SetValue(MultiChartInputDetailsProperty, value); }
}
public static readonly DependencyProperty MultiChartInputDetailsProperty =
DependencyProperty.Register("MultiChartInputDetails", typeof(ChartsData), typeof(MultiChartControl), new UIPropertyMetadata(new PropertyChangedCallback(MultiChartInputDetailsChanged)));
But the following callback method is not getting fired even once:
private static void MultiChartInputDetailsChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
MultiChartControl chart = d as MultiChartControl;
if (chart != null)
{
if (chart.ChartGrid.Children != null)
chart.ChartGrid.Children.Clear();
chart.InitilizeData();
}
MessageBox.Show("MultiChartInputDetailsChanged fired");
}
And the Main master control:
<multicharting:MultiChartControl x:Uid="multicharting:MultiChartControl_1"
MultiChartInputDetails="{Binding Path=MultiChartsInputDetails, ElementName=Chart, Converter={StaticResource DebugConverter}}"/>
This is because the DependencyProperty is not set to bind by two-way. This is done as follows:
DependencyProperty.Register("MultiChartInputDetails",
typeof(ChartsData),
typeof(MultiChartControl),
new FrameworkPropertyMetadat(default(ChartsData),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
MultiChartInputDetailsChanged)
Furthermore check whether there are any binding errors. If you do not want to provide a dependency property that performs a two-way binding per default then you could write your bindinga as follows:
<multicharting:MultiChartControl x:Uid="multicharting:MultiChartControl_1"
MultiChartInputDetails="{Binding Path=MultiChartsInputDetails,
Mode=TwoWay,
ElementName=Chart,
Converter={StaticResource DebugConverter}}"/>
I have a OneWayToSource binding that is not behaving as I expected when I set the DataContext of the target control. The property of the source is being set to default instead of the value of the target control's property.
I've created a very simple program in a standard WPF window that illustrates my problem:
XAML
<StackPanel>
<TextBox x:Name="tb"
Text="{Binding Path=Text,Mode=OneWayToSource,UpdateSourceTrigger=PropertyChanged}"
TextChanged="TextBox_TextChanged"/>
<Button Content="Set DataContext" Click="Button1_Click"/>
</StackPanel>
MainWindow.cs
public partial class MainWindow : Window
{
private ViewModel _vm = new ViewModel();
private void Button1_Click(object sender, RoutedEventArgs e)
{
Debug.Print("'Set DataContext' button clicked");
tb.DataContext = _vm;
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
Debug.Print("TextBox changed to " + tb.Text);
}
}
ViewModel.cs
public class ViewModel
{
private string _Text;
public string Text
{
get { return _Text; }
set
{
Debug.Print(
"ViewModel.Text (old value=" + (_Text ?? "<null>") +
", new value=" + (value ?? "<null>") + ")");
_Text = value;
}
}
}
The TextBox tb starts out with a null DataContext and therefore the binding is not expected to do anything. So if I type something in the text box, say "X", the ViewModel.Text property remains null.
If I then click the Set DataContext button I would have expected the ViewModel.Text property to be set to the "X" of the TextBox.Text property. Instead it is set to "". Certainly the binding is working because if I then type "Y" in the text box, after the "X", it sets the ViewModel.Text property to "XY".
Here is an example of the output (the last two lines are counter-intuitive because of the order of evaluation, but they definitely both occur immediately after typing the "Y"):
TextBox changed to X
'Set DataContext' button clicked
ViewModel.Text (old value=<null>, new value=)
ViewModel.Text (old value=, new value=XY)
TextBox changed to XY
Why is the ViewModel.Text property being set to "" instead of "X" when the DataContext is set?
What am I doing wrong? Am I missing something? Have I misunderstood something about binding?
Edit: I would have expected the output to be:
TextBox changed to X
'Set DataContext' button clicked
ViewModel.Text (old value=<null>, new value=X)
ViewModel.Text (old value=X, new value=XY)
TextBox changed to XY
Its a bug or perhabs not. Microsoft claims its by design. You first type x and then you kill DataContext by clicking on Button hence why the TextBox holds x and your viewModel.Text property gets newly initialized (its empty). When on datacontext changed getter will still be called. In the end you have no chance to fix this.
You can however use two way and let it be.
Here you will have to UpdateSource like below:
private void Button1_Click(object sender, RoutedEventArgs e)
{
Debug.Print("'Set DataContext' button clicked");
tb.DataContext = _vm;
var bindingExp = tb.GetBindingExpression(TextBox.TextProperty);
bingExp.UpdateSource();
}
TextBox has a Binding in it's TextProperty and when you set TextBox's DataContext, TextBox will update it's source (viewmodel.Text) , no matter which type of the UpdateSourceTrigger.
It's said that the first output in viewmodel
"ViewModel.Text (old value=<null>, new value=)"
is not triggered by UpdateSourceTrigger=PropertyChanged.
It's just a process of init:
private string _Text;
public string Text
{
get { return _Text; }
set
{
Debug.Print(
"ViewModel.Text (old value=" + (_Text ?? "<null>") +
", new value=" + (value ?? "<null>") + ")");
_Text = value;
}
}
Because it's not triggered by UpdateSourceTrigger=PropertyChanged, the viewmodel will not know the value of TextBox.Text.
When you type "Y",the trigger of PropertyChanged will working,so the viewmodel read text of TextBox.
There is a bug in .NET 4 with one way to source bindings that it calls getter for OneWayToSource bindings thats why you are having this problem.You can verify it by putting breakpoint on tb.DataContext = _vm; you will find setter is called and just after that getter is called on Text property.You can resolve your problem by manually feeding the viewmodel values from view before assigning the datacontext..NET 4.5 resolves this issue.
see here and here too
private void Button1_Click(object sender, RoutedEventArgs e)
{
Debug.Print("'Set DataContext' button clicked");
_vm.Text=tb.Text;
tb.DataContext = _vm;
}
You need Attached property:
public static readonly DependencyProperty OneWaySourceRaiseProperty = DependencyProperty.RegisterAttached("OneWaySourceRaise", typeof(object), typeof(FrameworkElementExtended), new FrameworkPropertyMetadata(OneWaySourceRaiseChanged));
public static object GetOneWaySourceRaise(DependencyObject o)
{
return o.GetValue(OneWaySourceRaiseProperty);
}
public static void SetOneWaySourceRaise(DependencyObject o, object value)
{
o.SetValue(OneWaySourceRaiseProperty, value);
}
private static void OneWaySourceRaiseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue == null)
return;
var target = (FrameworkElement)d;
target.Dispatcher.InvokeAsync(() =>
{
var bindings = target.GetBindings().Where(i => i.ParentBinding?.Mode == BindingMode.OneWayToSource).ToArray();
foreach (var i in bindings)
{
i.DataItem.SetProperty(i.ParentBinding.Path.Path, d.GetValue(i.TargetProperty));
}
});
And set binding in XAML:
extendends:FrameworkElementExtended.OneWaySourceRaise="{Binding}"
where {Binding} - is binding to DataContext.
You need:
public static IEnumerable<BindingExpression> GetBindings<T>(this T element, Func<DependencyProperty, bool> func = null) where T : DependencyObject
{
var properties = element.GetType().GetDependencyProperties();
foreach (var i in properties)
{
var binding = BindingOperations.GetBindingExpression(element, i);
if (binding == null)
continue;
yield return binding;
}
}
private static readonly ConcurrentDictionary<Type, DependencyProperty[]> DependencyProperties = new ConcurrentDictionary<Type, DependencyProperty[]>();
public static DependencyProperty[] GetDependencyProperties(this Type type)
{
return DependencyProperties.GetOrAdd(type, t =>
{
var properties = GetDependencyProperties(TypeDescriptor.GetProperties(type, new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.All) }));
return properties.ToArray();
});
}
private static IEnumerable<DependencyProperty> GetDependencyProperties(PropertyDescriptorCollection collection)
{
if (collection == null)
yield break;
foreach (PropertyDescriptor i in collection)
{
var dpd = DependencyPropertyDescriptor.FromProperty(i);
if (dpd == null)
continue;
yield return dpd.DependencyProperty;
}
}
I've created a custom control that extends the RichTextBox so that I can create a binding for the xaml property. It all works well as long as I just update the property from the viewmodel but when I try to edit in the richtextbox the property is not updated back.
I have the following code in the extended version of the richtextbox.
public static readonly DependencyProperty TextProperty = DependencyProperty.Register ("Text", typeof(string), typeof(BindableRichTextBox), new PropertyMetadata(OnTextPropertyChanged));
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var rtb = d as BindableRichTextBox;
if (rtb == null)
return;
string xaml = null;
if (e.NewValue != null)
{
xaml = e.NewValue as string;
if (xaml == null)
return;
}
rtb.Xaml = xaml ?? string.Empty;
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
In the view I've set the binding like such
<Controls:BindableRichTextBox Text="{Binding XamlText, Mode=TwoWay}"/>
In the viewmodel I've created the XamlText as a normal property with the NotifyPropertyChanged event being called on updates.
I want the bound XamlText to be updated when the user enters texts in the RichTextBox either on lostfocus or directly during edit, it doesn't really matter.
How can I change the code to make this happen?
You will need to listen to changes to the Xaml-property of the BindableRichTextBox and set the Text-property accordingly. There is an answer available here describing how that could be achieved. Using the approach described in that would the result in the following code (untested):
public BindableRichTextBox()
{
this.RegisterForNotification("Xaml", this, (d,e) => ((BindableRichTextBox)d).Text = e.NewValue);
}
public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
{
var binding = new Binding(propertyName) { Source = element };
var property = DependencyProperty.RegisterAttached(
"ListenAttached" + propertyName,
typeof(object),
typeof(UserControl),
new PropertyMetadata(callback));
element.SetBinding(property, binding);
}
As the SelectedItems property of the ListBox control is a normal property and not a dependency property to bind to, I have derived of the ListBox and created a new dependency property SelectedItemsEx.
But my XAML compiler keeps giving me the error
A 'Binding' cannot be set on the 'SelectedItemsEx' property of the
type 'MyListBox'. A 'Binding' can only be set on a DependencyProperty
of a DependencyObject.
Why my property is not recognized as a dependency property? Any help is appreciated, thank you!
XAML:
<MyListBox ItemsSource="{Binding MyData}" SelectedItemsEx="{Binding SelectedEx}"
SelectionMode="Extended"> ... </MyListBox>
ListBox' implementation:
public class MyListBox : ListBox
{
public readonly DependencyProperty SelectedItemsExProperty =
DependencyProperty.Register("SelectedItemsEx",
typeof(ObservableCollection<MyItemsDataType>),
typeof(MyListBox),
new PropertyMetadata(default(ObservableCollection<MyItemsDataType>)));
public ObservableCollection<MyItemsDataType> SelectedItemsEx
{
get
{
var v = GetValue(SelectedItemsExProperty);
return (ObservableCollection<MyItemsDataType>)v;
}
set { SetValue(SelectedItemsExProperty, value); }
}
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
base.OnSelectionChanged(e);
if (SelectedItemsEx != null)
{
SelectedItemsEx.Clear();
foreach (var item in base.SelectedItems)
{
SelectedItemsEx.Add((MyItemsDataType)item);
}
}
}
The DependencyProperty field must be static:
public static readonly DependencyProperty SelectedItemsExProperty = ...
Note also that in order to make your derived ListBox a little more reusable, you should not constrain the type of the SelectedItemsEx property. Use IEnumerable (or IList like SelectedItems) instead. Moreover, there is no need to specify a default value by property metadata, as it is null already and default(<any reference type>) is also null.
You will however have to get notified whenever the SelectedItemsEx property has changed. Therefore you have to register a change callback via property metadata:
public static readonly DependencyProperty SelectedItemsExProperty =
DependencyProperty.Register(
"SelectedItemsEx", typeof(IEnumerable), typeof(MyListBox),
new PropertyMetadata(SelectedItemsExPropertyChanged));
public IEnumerable SelectedItemsEx
{
get { return (IEnumerable)GetValue(SelectedItemsExProperty); }
set { SetValue(SelectedItemsExProperty, value); }
}
private static void SelectedItemsExPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var listBox = (MyListBox)obj;
var oldColl = e.OldValue as INotifyCollectionChanged;
var newColl = e.NewValue as INotifyCollectionChanged;
if (oldColl != null)
{
oldColl.CollectionChanged -= listBox.SelectedItemsExCollectionChanged;
}
if (newColl != null)
{
newColl.CollectionChanged += listBox.SelectedItemsExCollectionChanged;
}
}
private void SelectedItemsExCollectionChanged(
object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
...
}
}