IValueConverter Interface

IValueConverter Interface

 

Provides a way to apply custom logic to a binding.

 

Namespace:   System.Windows.Data
Assembly:   PresentationFramework (in PresentationFramework.dll)
Syntax

public interface IValueConverter

The IValueConverter type exposes the following members.

Methods

  NameDescription
Public method Convert Converts a value.
Public method ConvertBack Converts a value.
Top
Remarks

If you want to associate a value converter with a binding, create a class that implements the IValueConverter interface and then implement the Convert and ConvertBack methods. Converters can change data from one type to another, translate data based on cultural information, or modify other aspects of the presentation. For examples of some typical converter scenarios, see "Data Conversion" in Data Binding Overview.

Value converters are culture-aware. Both the Convert and ConvertBack methods have a culture parameter that indicates the cultural information. If cultural information is irrelevant to the conversion, then you can ignore that parameter in your custom converter.

The Convert and ConvertBack methods also have a parameter called parameter so that you can use the same instance of the converter with different parameters. For example, you can write a formatting converter that produces different formats of data based on the input parameter that you use. You can use the ConverterParameter of the Binding class to pass a parameter as an argument into the Convert and ConvertBack methods.

Examples

This example shows how to apply conversion to data that is used in bindings.

To convert data during binding, you must create a class that implements the IValueConverter interface, which includes the Convert and ConvertBack methods.

The following example shows the implementation of a date converter that converts the date value passed in so that it only shows the year, the month, and the day. When implementing the IValueConverter interface, it is a good practice to decorate the implementation with a ValueConversionAttribute attribute to indicate to development tools the data types involved in the conversion, as in the following example:

[ValueConversion(typeof(DateTime), typeof(String))]
public class DateConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DateTime date = (DateTime)value;
        return date.ToShortDateString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string strValue = value as string;
        DateTime resultDateTime;
        if (DateTime.TryParse(strValue, out resultDateTime))
        {
            return resultDateTime;
        }
        return DependencyProperty.UnsetValue;
    }
}


Once you have created a converter, you can add it as a resource in your Extensible Application Markup Language (XAML) file. In the following example, src maps to the namespace in which DateConverter is defined.

<src:DateConverter x:Key="dateConverter"/>


Finally, you can use the converter in your binding using the following syntax. In the following example, the text content of the TextBlock is bound to StartDate, which is a property of an external data source.

<TextBlock Grid.Row="2" Grid.Column="0" Margin="0,0,8,0"
           Name="startDateTitle"
           Style="{StaticResource smallTitleStyle}">Start Date:</TextBlock>
<TextBlock Name="StartDateDTKey" Grid.Row="2" Grid.Column="1" 
    Text="{Binding Path=StartDate, Converter={StaticResource dateConverter}}" 
    Style="{StaticResource textStyleTextBlock}"/>


The style resources referenced in the above example are defined in a resource section not shown in this topic.

 

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

 

 

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Community Content Add
Annotations FAQ
VB example
No VB code example was provided on this page.
I am fairly new to WPF and having been using Windows Forms DataGridView I wanted the same functionality as CellFormatting event. My objective was to hi-light a WPF DataGrid conditionally dependent on data value, in this case based on positive or negative. In order to do this I had to combine information from a number of MSDN pages as welll as other websites and blogs. Having succeeded, I thought I would put it in one place, to hopefully help someone else.

First here is the IValueConverter that I used.

<ValueConversion(GetType(Integer), GetType(Boolean))>
Public Class PositiveIntegerFlagConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If IsDBNull(value) Then
            Return False
        End If
        Dim anInteger As Integer = CType(value, Integer)
        If anInteger < 0 Then
            Return False
        End If
        Return True
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class

Next in the WPF page I added a namespace reference:

      xmlns:local="clr-namespace:MyNameSpace"

Then added:

    <Page.Resources>
        <local:PositiveIntegerFlagConverter x:Key="myConverter" />
    </Page.Resources>

Then in DataGrid

        <DataGrid x:Name="dgTargetVActual"
...
                  >
            <DataGrid.Columns>
                <DataGridTextColumn Header="+/- Pieces" Width="100" Binding="{Binding Path=AheadBehindPieces}" >
                    <DataGridTextColumn.CellStyle>
                        <Style>
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding AheadBehindPieces, Converter={StaticResource myConverter}}" Value="False">
                                    <Setter Property="TextBlock.Foreground" Value="Red" />
                                </DataTrigger>            
                            </Style.Triggers>
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>

A video, by Beth Massi that I used on route was:
http://msdn.microsoft.com/en-gb/vbasic/dd367843.aspx
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值