wpf string formatting NOT numbers or dates - wpf

This should have a simple solution, but I can't seem to find it.
I want to do something like the following, where I have a data binding with a string format. The field is a text field, and I'd like to display it with a suffix (but not change the underlying data).
<Label Name="field" Content="{Binding obj.field, StringFormat=\{0\} suffix}" />
So I want obj.field's value, for instance "value", to display as "value suffix".
Is it really necessary to use a ValueConverter (or whatever) to do this? I'm thinking that if it's possible with the StringFormat construction, then there's some magic format option I just haven't encountered.
This leads to a related question: where can I find a reference for WPF StringFormat? I can find the reference for the c# String.Format formatting options, but these don't all seem to work in WPF (like what I've tried above).

StringFormat will work if the target type is string. However, the type of Label's Content property is object. That is why the StringFormat has no effect. If you put a TextBlock inside the Label (or only use a TextBlock) and bind the Textblock's Text property, it should work fine.
<Label>
<TextBlock Text="{Binding obj.field, StringFormat=\{0\} suffix}" />
</Label>
If you have other reasons to want to bind the value to the Label, you could also do the following.
<Label DataContext="{Binding obj.field}">
<TextBlock Text="{Binding ., StringFormat=\{0\} suffix}" />
</Label>
Related question: I can't think of any reason why normal format strings that you can supply to string.Format() wouldn't work. They all should, both the standard and custom string. Here is a page with multiple examples. If there are any you find are not working, please provide examples.

Found a nice reference here with different examples : http://blog.stevex.net/string-formatting-in-csharp/

Related

Label % suffix in binding

I found something like this:
How to set WPF string format as percent wihout multiplying by 100?
I just want to have a '%' sign suffix after my number. my code looks like this
<Label Content="{Binding Path=ReportGridViewModel.FillingDegree, StringFormat=P}" />
I already tried this one too
<Label Content="{Binding ReportGridViewModel.Cgi, StringFormat={}{0}%}" />
in both cases I don't see any changes like I don't have any stringformat.
The StringFormat property of a Binding is only applied when the target property is of type String. In a Label, the target property Content, is of type Object, so StringFormat is not respected.
To get this to work in a label, use ContentStringFormat. If you were to use a TextBlock, you could use the StringFormat provided by Binding.
In the case of Label you need to use the ContentStringFormat property
<Label Content="{Binding Path=ReportGridViewModel.FillingDegree}"
ContentStringFormat="P" />

Xaml: Itemssource binding + fallbackValue

I've got a Listpicker with a DataBinding on the Itemssource-Property. Binding works fine. Now I want to define a FallbackValue. My problem is, that the FallbackValue is interpreted as a list: {'S','t','a','n','d','a','r','d'}, not as a single item 'Standard'. I'm looking for a solution to solve this problem. Any idea?
<toolkit:ListPicker x:Name="listPicker" ExpansionMode="FullScreenOnly" ItemsSource="{Binding Profilelist, ElementName=userControl, FallbackValue='Standard'}" SelectedIndex="0" />
The fallback behaviour is correct as the target expects an array (and a string an usable as an array of chars). There is no easy way to specify an array for the fallback.
I would suggest binding to a ViewModel list, instead of directly to the other control, so you can specify whatever default you want in the list. It does mean an extra binding and a property on your ViewModel (or code-behind... yuk) but element binding is not designed to have a fallback array, only single values.
If you can provide more code/Xaml I will be able to be more specific.

wpf - binding stringformat on label using string literal

I've binded the tooltip of a slider control to it's Value property and i'm trying to use StringFormat to make it display "Current Value {0} of 10" where the {0} is the Value property. Below is one of the various things I tried when trying to figure this out.
<Slider.ToolTip>
<Label>
<Label.Content>
<Binding StringFormat="Current Value {0} of 10"
ElementName="DebugLevelSlider"
Path="Value" />
</Label.Content>
</Label>
</Slider.ToolTip>
I am having issues finding examples online of how to use stringformat with string literals such as mine above. I see a lot of stringformat date/time/currency format conversion. I think I have a way to do this with a multibinding but it just seems like an extra amount of work than necessary. I hope that for string literal formatting I still do not have to write a custom converter.
In my app I find myself using a lot of extra labels next to items so getting an understanding in the stringformat will hopefully let me eliminate some of those unnecessary labels.
Label.Content is object so you can't use Binding.StringFormat there as the binding's target type must be string in order for it to work.
Two work arounds are: use TextBlock instead of Label and bind the Text property.
Use Label.ContentStringFormat i.e.
<Label ContentStringFormat="Current Value {0} of 10" Content={Binding ...} />
You only need to escape the string with {} if your first character is a {
For the ToolTip, you can check out WPF binding with StringFormat doesn't work on ToolTips.
As far as the StringFormat you specified above, you have to escape your string.
StringFormat="{}Current Value {0} of 10"
Here are a bunch of StringFormat examples.
http://blogs.msdn.com/b/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx

WPF: Textbox Binding with StringFormat={}{0:F2}. Don't show zero's

I am binding an object to a TextBox with the following XAML:
<TextBox Name="MyTextBox" Text="{Binding Path=MyValue, Mode=TwoWay, StringFormat={}{0:F2}}" />
Naturally when I bind a new object (which values are all still zero) the Text property is set to 0.00. I have several of these TextBoxes, which makes it tedious to delete every value before entering a new one.
At the moment I'm clearing these boxes in the Window_Loaded method using the FindVisualChildren method.
It just feels clunky though. Is there a neat way of doing this?
Try the following:
StringFormat={}{0:#.##}
It will format to two decimal places and won't show zeroes.

How to access property attributes on a data bound property in Silverlight?

For example, I have a simple textbox bound to a property:
<TextBox Text="{Binding FirstName, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" />
The property looks something like this:
[Display(Name="Last Name")]
public string LastName { ... }
So, given the textbox, I would like to get the Display Name property from the attribute. This will be used in a composite control that includes a fieldlabel and some other niceties.
Thanks in advance.
I am not able to attempt this at the moment so this may not be accurate or even possible. As soon as I get to a computer that I can try this I will...until then, this is just theory.
I'm guessing in your composite control you'll have something like this for each data bound field:
<TextBlock Text="{Binding FirstName, Mode=OneWay}" />
<TextBox Text="{Binding FirstName, Mode=TwoWay, ...}" />
What you'll probably need to do in order to create a converter that will look at the binding data for the Display attribute, and convert the value to the attribute value instead. This would cause the above block to look like this:
<TextBlock Text="{Binding FirstName, Mode=OneWay, Converter={StaticResource AttributeConverter}, ConverterParameter=Display}" />
<TextBox Text="{Binding FirstName, Mode=TwoWay, ...}" />
Here I passed in the Display as the parameter in case you wanted to access a different attribute.
Again this is just theory since I'm not able to currently test this and cannot recall if IValueConverter.Convert(object value, ...) passes the object in question or just the string value in this case. If it's just the string value, it probably isn't possible, though if it's the object instead, it will depend on how much access you have to the reflection namespace to evaluate the attributes.
As soon as I am able to, I'll throw the scenario together and try it out.
EDIT:
For some reason the sytax highlighter is giving me the finger when I try to paste code in this edit
Anyways, after trying this out in a little project, it don't think you can do this.
Based on my suggestion of making 2 data bound controls and using a converter for the one that consumes the attribute, I did the following:
Created the xaml for the databound control.
Create the Custom Attribute for testing
Created the Model with the decorated property for testing.
Created the converter to attempt to read the attribute from the property.
Here's where I got caught up. I wasn't able to obtain the data bound type from the IValueConverter.Convert(...) method. The value parameter came through as String as did the targetType parameter. While that was the primary hangup, the second was that I was unable to dynamically identify the property name that the control was data bound to. This could be remedied through a converter parameter possibly.
Now, I WAS able to read the attribute value if I supplied the type of my test Model with the decorated property so that much is possible but I wasn't able to dynamically identify the type on the fly.
The only other way I can think of is create some form of observer or converter prior to the data truly being bound to your custom control.
Good Luck

Resources