Concatenation of binding's path property in XAML - wpf

I have a question that is connected with setting path when binding in XAML, using WPF.
Imagine that my DataContext is of PropertyInfo type. PropertyInfo contains data about Property Name.
And in that object I nest (for example) TextBox which Text property I would like to bind to property with that name of another's element DataContext.
Something like that [it's pseudocode because it's not possible that way]:
<DataTemplate>
<TextBox Text={Binding ElementName=someElement, Path=DataContext. + {Binding Path=Name}}/>
</DataTemplate>
I want to create flexible view that's why I need to solve that problem.
Is there a way to achieve this without code behind?
Considering all the above, I think that I can make my question short and simply ask whether there is a way to concatenate string while setting binding's path.

I'm not sure if I understand correctly but is this something that multibinding would assist with?
<TextBlock Grid.Row="3" Grid.Column="1" Padding="5"><TextBlock.Text>
<MultiBinding StringFormat="[{0}, {1}]">
<Binding Path="LastName"></Binding>
<Binding Path="FirstName"></Binding>
</MultiBinding>
</TextBlock.Text>
</TextBlock>

Related

TextBox ConvertBack event doesn't fire for XML element

ValueFormattingConverter.Convert is called with the XmlElement. ConvertBack is never called. Why? Is there some obligation to pass binding directives down the chain? Is the use of the TextBox overriding its own binding settings? What can be done?
My TextBox
<TextBox Width="200"
Text="{Binding Path=., Converter={StaticResource valueFormattingConverter}}",
Mode=TwoWay,
NotifyOnSourceUpdated=True,
NotifyOnValidationError=True,
UpdateSourceTrigger=PropertyChanged}" />
Usage is rather convoluted. Starting at the top, we provide an XML element to a tab.
<TabItem.DataContext>
<Binding Source="{StaticResource mcf}",
XPath="mdf/press_information"/>
</TabItem.DataContext>
That tab contains a ItemsControl which builds TextBoxes through this ControlChooser which passes the binding along.
<ItemsControl.ItemTemplate>
<DataTemplate>
<W3V:ControlChooser RelativeSource="{RelativeSource AncestorType=W3V:ObjectList}",
Content="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
My converter class header. Convert method is called. ConvertBack never.
[ValueConversion(typeof(XmlElement), typeof(string))]
public class ValueFormattingConverter : IValueConverter
EDIT: The chosen answer basically says Path=. doesn't support 2-way binding. I believe it is the correct answer to the question. Very helpful to know, but "can't do that" doesn't solve the larger problem. So I have laid out the larger question here: Means of generating an editable form from XML.
The binding direction to source won't work with a {Binding Path=.}. This is because there is no bound property, but just the binding source object.
Hence there will never be a source update, and the ConvertBack method is never called, because that would mean to replace the source object.
In order to make your code work, you would have to bind to some property:
<TextBox Text="{Binding Path=SomeElement, ...}"/>

WPF Binding - Self Binding with its own DataContext

Anyone got a situation to bind the same DataContext to Text property (for example) in TextBlock.
I have to assign the DataContext to reflect some trigger based on the Data values from Datacontext in my style. at the same time, i need to bind with the same DataContext object to get the Text Property After applying some conversion on either IValueConverter/IMultivalueConverter.
As i know {Binding}, just bind with the current datacontext. But in the same scenario how to use converter with it?
Any suggestions will be appreciated.
<TextBlock Style="{StaticResource DataEntryTextBlock1}" Grid.Row="1"
DataContext="{Binding MyField1}"
Text="{Binding MyField1, Converter={StaticResource myConverter}}">
</TextBlock>
This XAML script does not work, as the Text binding is trying to look for the MyField1 variable inside the MyField1.
Thanks,
Vinodh
{Binding} is equivalent to {Binding Path=.} so in you case you can use
Text="{Binding Path=., Converter={StaticResource myConverter}}"
Binding.Path on MSDN
Optionally, a period (.) path can be used to bind to the current source. For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}"

Binding as a formatted string

I have a ListBox which hold a set of objects (linked via ItemsSource bind to an ObservableCollection). I haven't used Dynamic binding yet. It currently use the ToString() method of the object. The ToString() method shows a string this way : name (someOtherProperty)
However, even if the INotifyPropertyChanged is implemented and that i use an ObservableCollection, if i change an item property this string won't be updated.
I believe that this is because it only calls ToString once. instead i guess i have to use data binding but how i can form such a string with it ? << name (someOtherProperty) >>
Thanks.
You can use a multibinding, e.g. something like this:
<MultiBinding StringFormat="{}{0} ({1})">
<Binding Path="name"/>
<Binding Path="someOtherProperty"/>
</MultiBinding>
If you just let it execute ToString there is no proper binding at all, any notifications will have no effect.
You use it like this:
<ListBox ...>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<!-- The above binding here -->
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

How do I bind combobox text to legacy data not in the drop down list?

The drop-down list (itemssource) of my combobox contains new product request items. I want to bind to legacy data that is not in the drop-down list. To complicate things I'm using multibinding with an IMultiValueConverter to combine fields for display. Also, the names of bound fields do not match the names of the properties I'm bound to.
The combobox itemssource is a list of NewProductRequests. From this NPR object NewProdNumber and NewProdName are combined for display in the drop-down list by my type converter. The ConvertBack method returns the values NewProdNumber and NewProdNumberCombinedWithName. These two values will be saved to database fields with slightly different names. For this example I'll call them DBProdRequestNumber and DBProdRequestTitle.
I've succeeded in displaying and saving new items. The problem is I haven't figured out how to display legacy data that is not in the list. It's not in the list because it no longer qualifies as a new product request.
Here is the problem XAML (the itemssource is set in code-behind):
<ComboBox x:Name="NPRComboBox" IsSynchronizedWithCurrentItem="False" IsEditable="False">
<ComboBox.SelectedItem>
<MultiBinding Converter="{StaticResource combineNPRStuffMultiConverter}">
<Binding Path="DBProdRequestNumber" UpdateSourceTrigger="PropertyChanged"/>
<Binding Path="DBProdRequestTitle" UpdateSourceTrigger="PropertyChanged"/>
</MultiBinding>
</ComboBox.SelectedItem>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock DataContext="{Binding}">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource combineNPRStuffMultiConverter}">
<Binding Path="NewProdNumber" UpdateSourceTrigger="PropertyChanged"/>
<Binding Path="NewProdNumberCombinedWithName" UpdateSourceTrigger="PropertyChanged"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
A similar problem with a datagrid and combobox I solved using a DataGridTemplateColumn.CellEditingTemplate based on this MSDN Magazine example from Julie Lerman. Of course, in this case I'm not using a datagrid.
Thanks in advance for any help.
This answer (to my own question) was pulled from a comment in the NathanAW answer:
Unfortunately I can't include legacy items in the ItemsSource. The list is from a web service that is out of my control. I devised a kludgy solution which I don't really like (but it works)...Since I know the combobox is needed only for new records it is visible only when the user clicks "Add". In the same location I placed a textbox bound to the legacy data that is visible when NOT in add mode. So, I toggle the visiblity of each control as the app switches in and out of add mode. I'm sure there is a better way!
It seems that you might be able to simplify this by not using a Multi-Binding converter. If you have a collection of NPR objects, then you can set that as the ItemsSource for the listbox. Then use the DataTemplate to format how you want that item displayed.
With this setup, you can construct a template that shows multiple fields from the NPR object in a single TextBlock using something like:
<ComboBox
x:Name="NPRComboBox"
IsSynchronizedWithCurrentItem="False"
IsEditable="False"
SelectedItem={Binding SelectedNPR, Mode=TwoWay}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding Path=NewProdNumber, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
<Run> - </Run>
<Run Text="{Binding Path=NewProdNumberCombinedWithName, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
If you have additional properties on the NPR object that you'd like to access, you can add an additional section to the template.
Notice that the "selected" item is bound two-way back to a property on your ViewModel (or code-behind, or whatever). This would be something like:
public NPR SelectedNPR
{
get { ... }
set
{
...
// don't forget INotifyPropertyChanged
...
}
}
EDIT
Here is a sample that seems to do what you've indicted about showing legacy data in the "SelectionBox", but not in the drop down list. To test this, try running it in KaXaml or something. Then start typing "Hello 3" and see that it suggests "Hello 30". This indicates that the Combo knows about the item. Now drop the list down and see that it isn't in the list. If you arrow down with the arrow keys, it skips from "Hello 20" to "Hello 40".
The next step would be to setup your templates so that the ListBoxItem template's Visibility is bound to "IsLegacy" on your NPR object. Then add both legacy and new items to the ItemsSource collection and bind to the list.
<ComboBox IsEditable="True">
<ComboBoxItem >Hello 10</ComboBoxItem>
<ComboBoxItem >Hello 20</ComboBoxItem>
<ComboBoxItem Visibility="Collapsed">Hello 30</ComboBoxItem>
<ComboBoxItem >Hello 40</ComboBoxItem>
</ComboBox>

Dependency propery for ValueConverter or rebind control?

I have custom control with some text in content template:
<ControlTemplate TargetType="{x:Type local:TouchScreenKey}">
<TextBlock><ContentPresenter Content="{TemplateBinding Title, Converter={StaticResource CaseConverter}}" /></TextBlock>
</ControlTemplate>
and custom IValueConverter CaseConverter - with property UpperCase. So, when UpperCase property of converter set to true it converts text to upper case on binding. Everything goes fine if I change UpperCase in markup. But if i change property in runtime - nothing happens - because changing converter property not force my control to rebind.
How can I rebind control which uses converter on converter's property change?
As far as I know there is no way to tell converter to update all targets. Converter knows nothing about targets. It's just a stateless function, F(x), takes one value and returns another.
To update property you should ask WPF to do so. For example, if property is bound to some source property, you can implement INotifyPropertyChanged, and trigger PropertyChanged event. Or you can ask BindingOperations to get binding expression, and invoke UpdateTarget() manually.
Maybe converter isn't the best choice here? You may also want to consider using Attached Properties to change capitalization.
It may help someone - I found solution - using multibinding
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
<ContentPresenter>
<ContentPresenter.Content>
<MultiBinding Converter="{StaticResource MultiCaseConverter}">
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Title" />
<Binding ElementName="TouchKeyboard" Path="UpperCase" />
</MultiBinding>
</ContentPresenter.Content>
</ContentPresenter>
and wrote MultiCaseConverter - which convert first parameter depending from second (UpperCase)

Resources