Sometimes, we can use a value converter to display the bound data in another format or convert it to another type.
For example, if the path "C: \ ABC \ abc.exe133" of a file is saved in my data, I want to display it as cmdabc.exe in the foreground ".
First, we create a class for the ivalueconverter interface.
- ClassGetfilename: ivalueconverter
- {
- // The convert method is used to convert data into the desired display format.
- Public ObjectConvert (ObjectValue, type targettype,ObjectParameter, cultureinfo Culture)
- {
- Fileinfo Fi =NewFileinfo ((String) Value );
- ReturnFi. Name;
- }
- // The convertback method converts the displayed value to the original format. Because I do not need reverse conversion, an exception is thrown directly.
- Public ObjectConvertback (ObjectValue, type targettype,ObjectParameter, cultureinfo Culture)
- {
- Throw NewNotimplementedexception ();
- }
- }
To use this converter, We need to map the project namespace to The XAML. For example, if my project name is automatically updated, use local as the space name prefix.
Xmlns: Local = "CLR-namespace: automatic update"
Xmlns: Local = "CLR-namespace: automatic update"
For ease of use, we create a converter object in the resources set.
- <Window. Resources>
- <Local: getfilenameX: Key = "getfilename"> </Local: getfilename>
- </Window. Resources>
<Window. Resources> <br/> <local: getfilename X: Key = "getfilename"> </local: getfilename> <br/> </window. Resources>
Now we use staticresource to point to the converter where data is bound.
<Textblock>
- <Textblock. Text>
- <BindingPath = "FILENAME">
- <Binding. converter>
- <Local: getfilename> </local: getfilename>
- </Binding. converter>
- </Binding>
- </Textblock. Text>
- </Textblock>
Original article: http://blog.csdn.net/slzlren/article/details/6595905
For example:
Namespace converter {public class oppconverter: ivalueconverter {# region ivalueconverter member object ivalueconverter. Convert (object value, type targettype, object parameter, system. Globalization. cultureinfo culture) {If (targettype! = Typeof (bool) {Throw new invalidoperationexception ("the target must be a Boolean");} return! (Bool) value;} object ivalueconverter. convertback (object value, type targettype, object parameter, system. Globalization. cultureinfo culture) {Throw new notimplementedexception () ;}# endregion }}
The following is the XAML code:
<Grid> <Grid.Resources> <wf:OppConverter x:Key="OppositeConverter"/> </Grid.Resources> <StackPanel Margin="10,10,10,10"> <RadioButton x:Name="myRadio" IsChecked="True">Test convert</RadioButton> <RadioButton Height="20" Name="redYellow">Yellow</RadioButton> <RadioButton Height="20" Name="redGreen" VerticalAlignment="Bottom">Green</RadioButton> <TextBox Text="Sample Text" IsEnabled="{Binding ElementName=myRadio, Path=IsChecked, Converter={StaticResource OppositeConverter}}"/> </StackPanel> </Grid>
For example, when test convert is selected, inenable = false of textbox sample text