WPF databinding and converters - wpf

I'm trying to databind to a listbox like so:
<ListBox x:Name="MyListBox" Margin="0,0,0,65">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource MyConverter}}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The reason I am binding to the whole object and not a property is because my converter will need multiple properties of the object to build the string that it returns.
This works and my string is returned. But then when I change the ObservableCollection that this is based on the value doesn't change on the screen. If I bind to just a single property and change it, then the value does change.
What can I do differently? I can't bind to a single property since I need the entire object in the converter... And the ConverterParameter is already being used.

Remember, if you bind to the "main" property and the value of the main property itself isn't changed, the binding will have no reason to refresh itself. It has no clue that your converter is actually based off of a sub-property. What you can do is use a MultiBinding where you bind not only the "main" property, but also a specific sub-property. This gives your IMultiValueConverter implementation access to the main data object, but because you're also binding to the sub-property that's changing, will also be refreshed when that sub-property's value changes.

You can try using a MultiBinding which I believe updates whenever any of its Bindings are triggered. You can also use an IMultiValueConverter or just take advantage of the StringFormat of the binding.

Related

Silverlight telerik gridview force binding refresh with MVVM

This is the scenario:
I have a telerik gridview on my page, this is bound to a PagedCollectionView
with items of class "GekoppeldeOntvangstRegel",
this class implements INotifyPropertyChanged
Several columns have a CellTemplate with a TextBlock bound to an object of this class, like this:
<TextBlock Text="{Binding ConverterParameter='aantal', Converter={StaticResource GekoppeldeRegelDecimalFormatConverter}, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True}" HorizontalAlignment="Right" ToolTipService.ToolTip="{Binding ConverterParameter='aantal', Converter={StaticResource GekoppeldeRegelToolTipDecimalFormatConverter}}" />
This converter converts the "Aantal" property to a string with a specific number of decimals.
When I update the "Aantal" property from code with the OnPropertyChanged("Aantal") of course the binding isn't updated (since the textblock is bound to the entire object, not the property) so the old value is still visible.
How can I refresh the column contents from my viewmodel or object when the property changes?
When I bind directly to the "Aantal" property everything works perfectly (besides the converter not being applied, which is necessary)
As a workaround I now have created several extra properties on the "GekoppeldeOntvangstRegel" class.
These properties call the converter and return the right value with the right number of decimals.
On these properties raising OnPropertyChanged does work to refresh the bindings.
I'm not really happy with this solution but it works for now.

get context in converter?

I have a usercontrol whose the context is a given object Foo.
I have a textbox in readonly mode, whose the text changes according to a selected value in a combobox (which is bind two-way). The value of the textbox uses the values of a lot of fields in Foo.
For now, I have written a converter Text="{Binding ComboboxValue, Converter={StaticResource MyTextConverter}}, and code-behind, according to the ComboboxValue, I need to return a string composed of other values of Foo. The problem is I can't access the DataContext in the converter, and I can't pass it.
If I bind the context without Path (using Text="{Binding Converter={StaticResource ConnectionStringTextConverter}}), it won't trigger every time my value in the combobox changes (normal).
So, is it possible to it that way ? Or I'm forced to use the Selected event of the combobox ?
Thanks
PS: Actually, what I need is to bind the Text property of the textbox on my DataContext (no Path), but I need the binding to be evaluate each time a property change of the object change. Is this possible ?
You could use the DataContextProxy utility class like this:
Text={Binding ComboBoxValue, Converter={StaticResource MyTextConverter}, ConverterParameter={StaticResource DataContextProxy}}
and then in your converter grab the converter parameter and cast it to a DataContextProxy and use its DataSource property.

Databinding Not Updating When Using {Binding .} or {Binding}

I have an ObservableCollection of addresses that I am binding to a ListBox. Then in the ItemTemplate I am Binding to the current address record using {Binding .}. This results in my addresses displaying using their ToString method which I have setup to format the address. All is good, except if I update properties on an individual address record the list in the UI does not update. Adds/Deletes to the list do update the UI (using the ObservableCollection behavior). If I bind directly to properties on the address the UI does update (using the INotifyPropertyChanged behavior of the Address object).
My question is, is there a way to notify the UI of the change to the object as a whole so that I can still use this syntax or do I need to punt and put a DisplayText property on my address type that calls the ToString method and bind to that? FYI, this is an MVVM architecture so I don't have the luxury of calling Refresh on the ListBox directly.
Thanks for any help/ideas.
<ListBox x:Name="AddressList" ItemsSource="{Binding Addresses}" Background="Transparent" BorderBrush="Transparent"
Width="200" HorizontalAlignment="Left">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding .}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
When you bind to the Address object itself, the object itself -- that is, its identity -- doesn't change, even though its properties do. WPF therefore doesn't know to refresh the binding in this case.
So yes, you need to bind to a notifying property (or properties) rather than the whole object. As you say, one way to do this is to create a DisplayText property, and raise the PropertyChanged event for that property whenever something that affects the display text changes. Another is to use multiple TextBlocks in a horizontally oriented StackPanel, each bound to a particular property e.g.
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding HouseNumber}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding Street}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding City}" />
</StackPanel>
The advantage of the second approach is that it gives you flexibility in the UI to change how addresses are displayed, e.g. multiple lines, formatting, etc.; the downside is that it gets complicated if you have conditional logic e.g. an optional flat number or second address line.
I tried to reproduce the problem and succeeded.
I activated the step-into-.NET debugging options, and saw that WPF does not listen to INotifyPropertyChanged if the path in the binding is empty.
What worked to get a change to be reflected in the list box is to replace the whole object in the ObservableCollection. This triggers the INotifyCollectionChanged, with the Replace action.
But this may not be acceptable in your case. And it could be seen more like a hack than a solid solution.
I'd seriously consider having a DataTemplate for Address. There you should bind to the exact properties you need (which would create the listener for INotifyPropertyChanged). It is more flexible than ToString() and you may encounter cases where you have a need for ToString() to do something for non-UI stuff, which would create a conflict. And honestly, ToString is not really meant for UI stuff.

What's a good way to parameterize a ValueConverter used in a ControlTemplate?

A templated control I'm working on uses a ValueConverter like so:
<ListBox>
<ListBox.Resources>
<Controls:CodeDescriptionValueConverter x:Key="CodeDescriptionValueConverter"/>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource CodeDescriptionValueConverter}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is the default look that I supply in generic.xaml. When I use this control I'll want to pass different format strings into the converter. Is there a way to make that happen without providing the full ControlTemplate?
My first thought was that I could use ConverterParameter with a TemplateBinding to a property on the control, but I discovered that ConverterParameters can't be bound to. Another option could be to get access to the control from the ConvertTo method, then pick off that property. I'm not sure how to do that. Any options that would eliminate the need to completely re-template the control each time I use it would be helpful (it's a lot of Xaml).
In these situations, I generally do one of two things:
1) Bind to an object that has access to both the property you want to bind to the format string. In the the converter you will then have access to both the property and the format string.
2) Add properties to your data object/viewmodel/etc for the format string and the formatted text. Then bind to the formatted text properties. Assuming that you are using INotifyPropertyChanged, keep in mind that you will need to fire the propertychanged event for the formatted text property whenever you change the text or format string properties

WPF: Listbox, valueconverter

What is the easiest way to use a valueconverter with a listbox?
I'm setting the ItemSource to a List<> of objects at runtime, and it displays a textstring from the ToString() method. What I would like, though, is to pass the object through a valueconverter to get a completely different string value.
All the examples I have found makes a big deal of binding the list to something in xaml, and defining styles and templates to redesign the whole box, but I just want my values converted...
Use a data template with something like:
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter=....}" />
</...>
That's it. When you don't specify a path in your binding, it simply binds to the current object.

Resources