Binding from DependecyProperty to DataContext (ViewModel) in XAML - c#

Assume this situation:
I have created a new control ("MyControl") with DependencyProperty "SuperValue".
Now, in XAML i set "SuperValue" to "TestValue":
<local:MyControl SuperValue="TestValue" />
This control has a ViewModel (DataContext).
I want to pass value of DependencyProperty (in this example "TestValue") to property in ViewModel.
How can I do this?
Assume that ViewModel of my control do something calculations, for example: User inputs name of country, and control give him a time which is currently there.
The problem is: How can I provide the result of calculation? Assume that this is public property "Results" in ViewModel. I want to create a property like "TextBox.Text", "ListView.SelectedItem" which provides a part of ViewModel data "to outside".
For example TextBox and Text property:
<TextBox Text={Binding GiveMeTextValue} />
In this case DP "Text" provides to outside a ViewModel property which currently stores inputted text.
I want to use my control in the same way.

I don't know whether I get your question right: You want to set a static non-bound value in XAML to a DependencyProperty of the control and set a property on the control's DataContext to this static value? There is something wrong about your concept if you need to do this, why don't you provide this value on the ViewModel in an according field and bind the DP of the control to this field?
However, what you can do get what you want:
Define a PropertyChangedCallback when you register the DP:
// Dependency Property
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register("Test", typeof(string),
typeof(MyControl), new FrameworkPropertyMetadata("123", new PropertyChangedCallback(OnTestChanged)));
In the OnTestChanged method, cast your DataContext to the type of your ViewModel and set the according value on the ViewModel to the new value:
private static void OnTestChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyControl c = d as MyControl;
ViewModelType vm = c.DataContext as ViewModelType;
vm.Property = e.New;
Console.WriteLine(e.NewValue);
}
Is that what you're asking for?

What about setting the MyDependencyProperty from the setter of property SomethingValueInDataContext.
EDIT
You can set the controls DependencyProperty where the control is used and not on its declaration. This will work (local is namespace where control resides) -
<Grid>
<local:MyOwnControl MyDependencyProperty="{Binding Test}"/>
</Grid>
Same as like you can set the Width of the TextBox when you create an instance of it in xaml like this-
<TextBox Width="{Binding PropertyName}"/>

Notice, the root of your xaml is UserControl and not MyOwnControl. UserControl is the base class of MyOwnControl; your property is not defined in the base class. This is why you cannot reference MyDependencyProperty from within the root element of the UserControl.
Using your example, you can switch the binding and get your desired effect.
<UserControl
x:Class="namespace.MyOwnControl"
x:Name="root">
<UserControl.DataContext>
<local:ControlViewModel
Test={Binding MyDependencyProperty, ElementName=root}" />
</UserControl.DataContext>
</UserControl>

Since you are using a MVVM design paradigm all data should be relative to the ViewModel. So your DP should be set via the binding in your VM property.
If the test data is going to be used in Blend/VS designer you can check for that vs. Debug/Release... then do some sort of assignment to your property based off of that check for testing.

You could add a property to MyControl called InitialSuperValue that when set, sets the value of SuperValue. Then write some XAML like this:
<local:MyControl InitialSuperValue="TestValue" SuperValue="{Binding SuperValueInViewModel, Mode=OneWayToSource}" />

Related

How to databind property from view model to custom user control in WPF? [duplicate]

This question already has an answer here:
How to pass data from MainWindow to a User Control that's inside the MainWindow?
(1 answer)
Closed 2 years ago.
I have a custom control that I created to test how binding works. It has a dependency property that I want to bind from another view and also I want it to update when binded property raises PropertyChanged using INotifyPropertyChanged:
public string BindLabelText
{
get { return (string)GetValue(BindLabelTextProperty); }
set { SetValue(BindLabelTextProperty, value); }
}
public static readonly DependencyProperty BindLabelTextProperty =
DependencyProperty.Register("BindLabelText", typeof(string), typeof(BindingControl),
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
In my control I bind dependency property like this:
<TextBlock
Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
Text="{Binding ElementName=TestControl, Path=BindLabelText, FallbackValue=BindLabelText}"
FontSize="20"/>
And I use control like this:
<local:BindingControl BindLabelText="Static main window value" />
<local:BindingControl BindLabelText="{Binding HeaderLabel, FallbackValue=HeaderLabel}" />
<Button Content="Change MainWindow property" Command="{Binding ChangeMainTextCommand}"/>
TextBlock text value is set with a static value but it does not work when I try to bind it to a property. In both views I set DataContext to ViewModel in code behind:
this.DataContext = new BindingControlViewModel();
Edit:
Added my code to github. Like I said in the comments I'm trying to bind property on MainWindowViewModel which is the DataContext for my parent View (MainWindow) to my User Control DP BindLabelText. User Control in addition to DP also has its own ViewModel. My goal is to have User Control that will update when bound property from MainWindowViewModel updates.
I managed to solve it by setting my control DataContext to grid like MyGrid.DataContext = new BindingControlViewModel(); instead of setting it on the control itself like this.DataContext = new BindingControlViewModel();.

Set property in ViewModel within other View

I have a WPF-Application with a Window and a UserControl. The UserControl is implemented with the MVVM-Pattern. So in the view I have a Label which displays the value of a string-property called InfoMessage in the ViewModel.
In the Window I added an instance of this UserControl by
<views:ItemInfoView Grid.Row="3" Grid.Column="1" x:Name="itemInfoView"/>
Now I want to set the InfoMessage from the XAML of my Window. Currently I have no idea how to achieve this in xaml. In code-behind I could access the DataContext of my control and cast it to ItemInfoViewModel and the set the value like:
((ItemInfoViewModel)itemInfoView.DataContext).InfoMessage = "Hello World";
But I hope there's a way to do this in pure XAML. Does anyone know if this is possible and how?
You need to add a Dependency Property to your user control:
// Your property
public string InfoMessage{get;set;}
// Register Dependency Property
public static readonly DependencyProperty InfoMessageProperty =
DependencyProperty.Register("InfoMessage", typeof(string), typeof(ItemInfoView),
new UIPropertyMetadata(true));
Then you should be able to just set or bind InfoMessage directly:
<views:ItemInfoView Grid.Row="3" Grid.Column="1" InfoMessage="Whatever"/>

To use (DataContext) or not to use

I've got a dilemma regarding the DataContext. Let's inspect the following piece of XAML:
<Window xmlns:my="clr-namespace:MyNamespace.Controls"
... >
...
<my:MyControl Name="{Binding Prop1}" Value="{Binding Prop2}" />
</Window>
Obviously, the Window's code-behind contains something like:
DataContext = someViewModel;
Author's intentions are clear - he wants to bind MyControl's Name and Value to Window's DataContext's Prop1 and Prop2. And this will of course work. Unless. (dramatic pause)
Unless MyControl is a composite UserControl, which also wants to take advantage of short notation of bindings and sets its DataContext to its own viewmodel. Because then it will become clear, that the bindings in Window's XAML actually bind to MyControl's DataContext (previously inherited from Window's one) and now they will stop working (or worse, will keep working if MyControl's viewmodel actually contains properties named Prop1 and Prop21).
In this particular case solution is to bind in Window's code explicitly:
<Window x:Name="rootControl"
xmlns:my="clr-namespace:MyNamespace.Controls"
... >
...
<my:MyControl Name="{Binding ElementName=rootControl, Path=DataContext.Prop1}"
Value="{Binding ElementName=rootControl, Path=DataContext.Prop2}" />
</Window>
TL;DR If we're using short notation of bindings (when binding to DataContext) we may encounter quite tough to nail bugs resulting from bindings suddenly pointing to wrong DataContext.
My question is: how to use short binding notation without risk, that I'll bind to wrong DataContext? Of course I may use the short notation when I'm sure, that I'll be using inherited DataContext and long notation when I'm sure, that control will modify its DataContext. But that "I'm sure" will work only until first mistake, which will consume another hour of debugging.
Maybe I'm not following some MVVM rule? E.g. for example DataContext should be set only once on the top level and all composited controls should bind to something else?
1 I've gone through that, actually. The Window's DataContext contained a property named (say) Prop and the control replaced its DataContext with a class, which also contained a property Prop and everything worked fine. Problem appeared when I tried to use (unconsciously) the same pattern with non-matching property names.
By request:
Fragment of MyControl's code:
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
// Using a DependencyProperty as the backing store for Name. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(MyControl), new PropertyMetadata(null));
public int Value
{
get { return (int)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(int), typeof(MyControl), new PropertyMetadata(0));
Window's viewmodel:
public class WindowViewmodel : INotifyPropertyChanged
{
// (...)
public string Prop1
{
get
{
return prop1;
}
set
{
prop1 = value;
OnPropertyChanged("Prop1");
}
}
public int Prop2
{
get
{
return prop2;
}
set
{
prop2 = value;
OnPropertyChanged("Prop2");
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Now assume, that on changing of Name and Value dependency properties, MyControl generates some viewmodel and executes the code:
model = new MyControlViewModel(Name, Value);
this.DataContext = model;
And internal MyControl controls bind to this DataContext.
From now on, the original Name and Value bindings will no longer work.
Unless MyControl is a composite UserControl, which also wants to take advantage of short notation of bindings and sets its DataContext to its own viewmodel.
And that's where I stopped reading. This is, imho, a MVVM anti-pattern.
The reason for this is twofold. First, you screw with anybody who is using the control. "Hey," you say, "you can't bind your stinky VM to my beautiful UI. You have to use MY custom VM!" But what if your VM is hard to use, lacks logic or features needed by the overall application? What happens when, to use your UI, we have to translate our VM/models back and forth with your VM? Pain in the butt.
Second is that your custom control is UI. Its logic is UI logic, and so it is unnecessary to use a view model. It is better to expose DependencyProperties on your control and update your UI as necessary. That way anybody can bind to your UI and use it with any model or view model.
You can solve your problems by simply not using what you call a 'composite control. While I understand that you want to encapsulate some functionality in the associated view model, you don't need to set the view model to the UserControl.DataContext internally.
What I mean by this is that you can have a view model for any or all of your UserControls, but they're data classes, not UI classes, so keep them out of the view code. If you use this method of adding DataTemplates into Resources, then you won't need to set any DataContext properties at all:
<DataTemplate DataType="{x:Type ViewModels:YourUserControlViewModel}">
<Views:YourUserControl />
</DataTemplate>
The final difference is that you should add your view model for your UserControls as properties in a parent view model. This way, you still have no duplicated code (except maybe just a property declaration) and more importantly, you have no Binding problems from mixing DataContext values.
UPDATE >>>
When using this DataTemplate method of hooking up views and view models, you can display your view by Binding your view model property to the Content property of a ContentControl like this:
<ContentControl Content="{Binding YourViewModelProperty}" />
At run time, this ContentControl will be rendered as whatever view or UserControl that you defined in the DataTemplate of the relevant type for that property. Note that you shouldn't set the x:Key of the DataTemplate, otherwise you'd also need to set the ContentControl.ContentTemplate property and that can limit the possibilities afforded by this method.
For example, without setting the x:Key property on your DataTemplates, you could have a property of a base type and by setting it to different sub class, you can have different views for each from the one ContentControl. That is the basis of all of my views... I have one property of a base class view model data bound like this example and to change views, I just change the property to a new view model that is derived from the base class.
UPDATE 2 >>>
Here's the thing... you shouldn't have any 'proxy' object in your UserControls doing anything... it should all be done through properties. So just declare a DependencyProperty of the type of that object and supply it from the view model through data Binding. Doing it this way means that it will be easy to test the functionality of that class, whereas testing code behind views is not.
And finally, yes, it's perfectly fine doing this in MVVM:
<Controls:SomeUserControl DataContext="{Binding SomeViewModelProperty}" />
The overriding goal of MVVM is just to provide separation between the UI code and the view model code, so that we can easily test what's in the view models. That is why we try to remove as much functionality code from the views as possible.
within a usercontrol you should never set the datacontext to "this" or a new viewmodel. a developer/user of your MyUsercontrol expect that the datacontext inherit from top to bottom (from mainwindow to your myusercontrol).
your usercontrol xaml should use element binding
MyUserControl.xaml
<UserControl x:Name="uc">
<TextBlock Text="{Binding ElementName=uc, Path=Name}"/>
<TextBlock Text="{Binding ElementName=uc, Path=Value}"/>
this means your following code will work now in every situation
<Window xmlns:my="clr-namespace:MyNamespace.Controls">
<my:MyControl Name="{Binding Prop1}" Value="{Binding Prop2}" />
</Window>
the property Prop1 from Datacontext mainwindow is bound to the DP Name from your MyUsercontrol and the Textblock.Text within your MyUsercontrol is bound to the DP Name.
I've never met such a problem. It seems to be a little bit theoretical to me but maybe because of my approach to working with DataContext in WPF.
I minimize the explicit use DataContext property. I set it manually only for windows.
I have one dedicated method which is responsible for displaying new windows and it is the only one place where the DataContext property is set explicitly.
DataContext property for Windows is set to root ViewModel which contains child ViewModels, which contain...
I allow WPF to select which View should be used to display given a ViewModel by using DataTemplate
In my application I have a single ResourceDictionary which contains mappings between all ViewModels and Views.

My WPF user control has one-way bindings and I don't know why

I have created a very simple user control that shows a ColorPicker (from the WPF Extended Toolkit) and a text field for its hex code:
<UserControl x:Class="HexColorPicker"> <!-- namespace declarations omitted -->
<UserControl.Resources>
<glue:ColorToRgbHex x:Key="colorToHex"/> <!-- custom converter I made -->
</UserControl.Resources>
<StackPanel Orientation="Horizontal" Name="layoutRoot">
<Label Content="#"/>
<TextBox Text="{Binding SelectedColor, Converter={StaticResource colorToHex}}"/>
<extToolkit:ColorPicker SelectedColor="{Binding SelectedColor}"/>
</StackPanel>
</UserControl>
And here is the backing code:
public partial class HexColorPicker : UserControl
{
public static readonly DependencyProperty SelectedColorProperty
= DependencyProperty.Register("SelectedColor", typeof(Color), typeof(HexColorPicker));
public HexColorPicker()
{
InitializeComponent();
layoutRoot.DataContext = this;
}
public Color SelectedColor
{
get { return (Color)GetValue(SelectedColorProperty); }
set { SetValue(SelectedColorProperty, value); }
}
}
The layoutRoot.DataContext shenanigans come from this place I found.
I then use my control like that:
<me:HexColorPicker SelectedColor="{Binding MyColor}"/>
And it somewhat works. The text field and the color picker are in sync: when one changes, the other changes as well. However, the control and the model object aren't two-way synced: my control will update if I change the model object's MyColor property, but the MyColor property will not update when I change it with my control.
What am I doing wrong? Why is the binding one-way from my model to my control only?
Change your DependencyProperty Declaration to:
public static readonly DependencyProperty SelectedColorProperty = DependencyProperty.Register("SelectedColor", typeof (Color), typeof (HexColorPicker), new FrameworkPropertyMetadata(default(Color),FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
As I recall, bindings that convert between types sometimes default to OneWay binding.
From the reference for BindingMode.Default (http://msdn.microsoft.com/en-us/library/system.windows.data.bindingmode.aspx):
Uses the default Mode value of the binding target. The default value varies for each dependency property. In general, user-editable control properties, such as those of text boxes and check boxes, default to two-way bindings, whereas most other properties default to one-way bindings. A programmatic way to determine whether a dependency property binds one-way or two-way by default is to get the property metadata of the property using GetMetadata and then check the Boolean value of the BindsTwoWayByDefault property.
It looks like the problem is that your control isn't seen as a 'user-editable' control.
The easiest solution is to specify Mode=TwoWay in your binding.

Binding not works on DependencyProperty

I have a window which has a usercontrol in it . This usercontrol's RequestObject property bound to SearchArgumentObject property of ViewModel of the window.
This is listing from my window class
<Grid DataContext="{Binding SearchArgumentObject, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<guiLib:RegCardSearchForm x:Name="SearchParametrsUC" Grid.Row="1" RequestObject="{Binding .,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
In Usercontrol class I created dependency property:
This is listing from my userControl class
public static DependencyProperty RequestObjectProperty = DependencyProperty.Register("RequestObject", typeof(RegistrationCardSearch), typeof(RegCardSearchForm));
public RegistrationCardSearch RequestObject
{
get
{
return (RegistrationCardSearch)GetValue(RequestObjectProperty);
}
set
{
SetValue(RequestObjectProperty, value);
}
}
On the level of the usecontrol everything works fine and RequestOject property changed.
But in my window class I can't see modification of SearchArgumentObject property which was made in usercontrol.
How can I get modefied property value? I think answer to this question is very trivial but I can't find solution.
Setting the DataContext on the Grid isn't doing anything but breaking the two-way linking of your properties. Skip the extra step and bind the VM property to the control property that you want to pick up changes from instead:
<Grid>
<guiLib:RegCardSearchForm x:Name="SearchParametrsUC" Grid.Row="1"
RequestObject="{Binding SearchArgumentObject, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
The code for your Window class is setting the DataContext of the Grid to a property obtained from a binding to a property on another object's DataContext further up the tree. Do you have the Window's DataContext set elsewhere?
Let's say that the object which is supplying the SearchArgumentObject is named SearchWindowViewModel. In the code-behind of the Window, you would have the following code (in the constructor, for example):
DataContext = new SearchWindowViewModel();
Now, all the properties that SearchWindowViewModel exposes are available to the Window. To bind the SearchWindowViewModel.SearchArgumentObject to the UserControl's RequestObject property, you would have the following XAML:
<Grid>
<guiLib:RegCardSearchForm x:Name=SearchParametersUC Grid.Row=1
RequestObject={Binding SearchArgumentObject />
</Grid>
If you don't want to set the Window's DataContext, you can set the Grid's DataContext using the same type of code as I used above, and the binding in the XAML would remain the same.
Hope that helps.

Categories

Resources