How to debug databinding - c#

I'm new to data-binding and I am having a hard-time setting it up for my WPF application:
I have a class Test which implements INotifyPropertyChanged and a property Text.
When I do this in the code-behind:
Binding b = new Binding("Text");
b.Source = Test;
label1.SetBinding(ContentProperty, b);
everything works great.
When I do the same thing in XAML:
Content="{Binding Source=Window.Test, Path=Text}"
The label content does not update.
I would like to avoid having to do this in the code-behind, what am I doing wrong?

The easiest solution is to give a name to the Window in XAML (e.g. root) and use ElementName to define the binding source:
Content="{Binding ElementName=root, Path=Test.Text}"

For simplicity, set the window DataContext to your Test instance:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Test
{
Text = "Hello, World!"
};
}
}
Then declare databinding in XAML:
Content="{Binding Path=Text}"

what am I doing wrong?
You are making unfounded assumptions about how something ought to work about which you do not have much of a clue. You are dealing with two fundamentally different languages here and just because you want WPF to interpret Window.Test as a reference to some specific window you had in mind does not make it so.
XAML is fundamentally string-based, for the most part strings are converted to primitive types like ints and doubles, e.g. when you set the height of a control you pass a string to a property of type double. The XAML parser knows via reflection that the property is of type double and tries to convert the string (using a default value converter if no other has been specified). Now what do you think happens if a property is of type object? What is the parser to do? Well, it is not going to do anything as a string is already an object.
Guess what type Binding.Source has and what the source object of your binding will be when you write Window.Test...

Related

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.

How can I bind a xaml property to a static variable in another class?

I have this xaml file in which I try to bind a Text-block Background to a static variable in another class, how can I achieve this ?
I know this might be silly but I just moved from Win-forms and feeling a little bit lost.
here is what I mean:
<TextBlock Text="some text"
TextWrapping="WrapWithOverflow"
Background="{Binding Path=SomeVariable}" />
First of all you can't bind to variable. You can bind only to properties from XAML.
For binding to static property you can do in this way (say you want to bind Text property of TextBlock) -
<TextBlock Text="{Binding Source={x:Static local:YourClassName.PropertyName}}"/>
where local is namespace where your class resides which you need to declare above in xaml file like this -
xmlns:local="clr-namespace:YourNameSpace"
You can't actually bind to a static property (INotifyPropertyChanged makes sense on instances only), so this should be enough...
{x:Static my:MyTestStaticClass.MyProperty}
or e.g.
<TextBox Text="{x:Static my:MyTestStaticClass.MyProperty}" Width="500" Height="100" />
make sure you include the namespace - i.e. define the my in the XAML like xmlns:my="clr-namespace:MyNamespace"
EDIT: binding from code
(There're some mixed answers on this part so I thought it made sense to expand, have it in one place)
OneTime binding:
You could just use textBlock.Text = MyStaticClass.Left (just careful where you place that, post-init)
TwoWay (or OneWayToSource) binding:
Binding binding = new Binding();
//binding.Source = typeof(MyStaticClass);
// System.InvalidOperationException: 'Binding.StaticSource cannot be set while using Binding.Source.'
binding.Path = new PropertyPath(typeof(MyStaticClass).GetProperty(nameof(MyStaticClass.Left)));
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
this.SetBinding(Window.LeftProperty, binding);
...of course if you're setting Binding from the code remove any bindings in XAML.
OneWay (property changes from the source):
And if you'd need to update the target (i.e. the control's property, Window.Left in this case) on the source property changes, that can't be achieved with the static class (as per my comment above, you'd need the INotifyPropertyChanged implemented, so you could just use a wrapper class, implement INotifyPropertyChanged and wire that to a static property of your interest (providing you know how to track you static property's changes, i.e. this is more of a 'design' issue from this point on, I'd suggest redesigning and putting it all within one 'non-static' class).
You can use the newer x:Bind to do this simply using:
<TextBlock Text="{x:Bind YourClassName.PropertyName}"/>

Binding from DependecyProperty to DataContext (ViewModel) in XAML

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}" />

Property on static resource converter not bound

I have a value converter with a property I would like to bind to, but the binding never happens, i.e. the dependency property in my value converter always is null.
Background: I want to bind an enum to a combo box but have control over the text that is being displayed.
I implemented the value converter like this:
public class EnumDisplayer : DependencyObject, IValueConverter
{
public static readonly DependencyProperty LocalizerProperty =
DependencyProperty.Register(
"Localizer", typeof(ILocalizer), typeof(EnumDisplayer),
new PropertyMetadata(default(ILocalizer), OnLocalizerChanged));
public ILocalizer Localizer
{
get { return (ILocalizer) GetValue(LocalizerProperty); }
set { SetValue(LocalizerProperty, value); }
}
private static void OnLocalizerChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
// ...
}
//...
}
And I bind it like this:
<UserControl.Resources>
<Common:EnumDisplayer x:Key="companyTypes"
Localizer="{Binding CompanyTypeEnumLocalizer}" />
<!-- ... -->
</UserControl.Resources>
My class is an adapted version of the EnumDisplayer.
I fail to understand, why OnLocalizerChanged is never called. Can anyone provide some insight?
(Stack Team correct me if I am wrong)... ValueConverters do not automatically support in binding and there are reasons...
They arent really something that the WPF framework is actively aware of, given that they dont lie on visual or logical tree.
They are used as part of inner markup extensions. This is a merky area. Unless they implement marrkup extensions on their own, they would be bound to.
Although there are ways..
Straightforward way is to use MultiBinding instead of single binding. The second binding will replace your converter's need to host a dependncy property.
http://www.codeproject.com/KB/WPF/AttachingVirtualBranches.aspx
I hope this helps.
I think this may be because the ResourceDictionary in which you are creating the instance is not part of the visual tree, so it cannot find the DataContext and the Binding therefore always returns null.
You may be able to get around this by giving your UserControl an x:Name attribute and then binding using ElementName and DataContext.PropertyName:
<UserControl x:Name="Root">
<UserControl.Resouces>
<Common:EnumDisplayer x:Key="companyTypes"
Localizer="{Binding DataContext.CompanyTypeEnumLocalizer, ElementName=Root}" />
</UserControl.Resouces>
</UserControl>

Binding in code question

I am using the same window that serves two purposes. Inside my window, i have a listview that I want to bind to DIFFERENT objects based on the purpose.
Actually its just a window that takes in import files.
So initially I had this.
<ListView Grid.Row="1" Name="_lvValues"
DataContext="{Binding ElementName=_listbox,Path=SelectedItem}"
ItemsSource="{Binding Path=DataTable(from selectedItemObject)}">
For the other purpose I had to do this
<ListView Grid.Row="1" Name="_lvValues"
DataContext="{Binding ElementName=ClassName,Path=Object}"
ItemsSource="{Binding Path=DataTable(from Object)}">
I want to do this in an if/else statement during the initialization of the window (constructor). So...
if (windowType == Type1)
// SetBinding to using listbox
else
// SetBinding to using Object
I tried this After initialize component
binding = new Binding("DataTable");
binding.Source = new Binding("ListBox.SelectedItem");
_lvValues.SetBinding(ListView.ItemsSourceProperty, binding);
But obviously it didn't work and i have no idea how to proceed.
Reason I need this is, the first window type there is a LIST of file, where second window type only has ONE file so it would not be right to show a listbox with just one file.
Thanks and Regards,
Kev
If your Xaml is an accurate description of your binding you just need to translate it into the two resulting bindings; should be something like this for the first case:
Binding contextBinding = new Binding("SelectedItem");
contextBinding.Source = _listbox;
_lvValues.SetBinding(ListView.DataContextProperty, contextBinding);
Binding itemsBinding = new Binding("DataTable");
_lvValues.SetBinding(ListView.ItemsSourceProperty, itemsBinding);
and the second case is probably this:
Binding contextBinding = new Binding("Object");
contextBinding.Source = ClassName;
_lvValues.SetBinding(ListView.DataContextProperty, contextBinding);
Binding itemsBinding = new Binding("DataTable");
_lvValues.SetBinding(ListView.ItemsSourceProperty, itemsBinding);
(Since the ItemsSource-Binding is always the same and just depends on the DataContext you could refactor it to be outside of the if-clause or in the Xaml altogether i think)

Categories

Resources